ローカルの音楽を再生するアプリを作ろうとしているのですが、残念ながらiOS5でAVQueuePlayerを使ってバックグラウンドでオーディオを再生することができません。
私の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
しかし、効果的に曲が始まることはありません...
私のコードの何が問題なのか誰か教えてもらえますか??
どうもありがとう。