2012-03-01 41 views
0

我試圖構建應用程序播放本地音樂,但不幸的是,我無法使用AVQueuePlayer在iOS5中進行背景音頻播放。無法在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 

但沒有歌曲有效啓動...

誰能告訴我什麼是錯我的代碼?

非常感謝。

回答

0

試評下一行

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

,如果它工作,那麼你需要一個觀察者添加到mAudioPlayer爲「currentItem.status」時,狀態AVPlayerStatusReadyToPlay然後結束後臺任務