0

我正在尝试构建一个应用程序来播放本地音乐,但不幸的是,我无法使用 AVQueuePlayer 在 iOS5 的后台进行音频播放。

在我的 ViewDidLoad 中,我得到了以下代码:

// 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];

这是我的“playerItemDidReachEnd”方法:

- (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;
}

当我开始播放时,它可以工作,并在我关闭屏幕时继续播放。但是当歌曲结束时,这里是日志

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

但是没有一首歌能有效地开始......

谁能告诉我我的代码有什么问题??

非常感谢。

4

1 回答 1

0

尝试评论下一行

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

如果它有效,那么当状态 AVPlayerStatusReadyToPlay 然后结束后台任务时,您需要为“currentItem.status”添加一个观察者到 mAudioPlayer

于 2012-05-18T15:18:12.537 回答