0

I'm trying to build an app to play local music, but unfortunately, i'm unable to do audio playback in background in iOS5 with AVQueuePlayer.

In my ViewDidLoad, i got this code :

// Player setup
mAudioPlayer = [[AVQueuePlayer alloc] init];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
[mAudioPlayer addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1.0, 1) queue:NULL usingBlock:^(CMTime time) {
    [self updatePositionOnDisplay]; 
}];

// Audio session setup
NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryErr];
[[AVAudioSession sharedInstance] setActive: YES error: &activationErr];

Here is my "playerItemDidReachEnd" method:

- (void)playerItemDidReachEnd:(NSNotification*)notification 
{
    NSLog(@"playerItemDidReachEnd");

    UIBackgroundTaskIdentifier newTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:newTaskID];
    }];
    NSLog(@"playerItemDidReachEnd 2");

    NSLog(@"searching next song");
    mCurrentSong = [self getNextSongWithIsSwitched:NO];
    if(mCurrentSong != nil){
        NSLog(@"Start : %@ - %@", mCurrentSong.artist, mCurrentSong.title);

        mTapeTitle.text = [NSString stringWithFormat:@"%@ - %@", mCurrentSong.artist, mCurrentSong.title];

        AVPlayerItem* i = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:mCurrentSong.path]];

        if(i != nil){
            [mAudioPlayer insertItem:i afterItem:nil];
        }else
            NSLog(@"BING!! no AVPlayerItem created for song's path: %@", mCurrentSong.path);

        [i release];
    }else{
        NSLog(@"no song found");
        [mAudioPlayer pause];
        isPlaying = NO;        
        [mPlayButton setSelected:NO];
    }

    [[UIApplication sharedApplication] endBackgroundTask:newTaskID];
    newTaskID = UIBackgroundTaskInvalid;
}

When I start the playback, it works, and keep playing when i switch off the screen. BUT when the song is over, here are the logs

2012-03-01 10:00:27.342 DEMO[3096:707] playerItemDidReachEnd
2012-03-01 10:00:27.360 DEMO[3096:707] playerItemDidReachEnd 2
2012-03-01 10:00:27.363 DEMO[3096:707] searching next song
2012-03-01 10:00:27.381 DEMO[3096:707] Start : Moby - Ah-Ah

But no song start effectively...

Can anyone tell me what's wrong with my code ??

Thanks a lot.

colletjb
  • 279
  • 3
  • 16

1 Answers1

0

try to comment next lines

[[UIApplication sharedApplication] endBackgroundTask:newTaskID];
newTaskID = UIBackgroundTaskInvalid;

if it works then you need to add an observer to a mAudioPlayer for "currentItem.status" when status AVPlayerStatusReadyToPlay then end background task

mashe
  • 89
  • 1
  • 7