2016-08-01 101 views
0

我爲我的應用程序製作了鬧鐘功能,當我設置了鬧鐘消息時,我可以用AVAudioPlayer播放音樂曲目,它在後臺模式下運行良好。但是,如果此時我打開Youtube應用並播放視頻,那麼AVAudioPlayer不起作用。當Youtube播放時,AVAudioPlayer無法在背景上播放

請告訴我,爲什麼出現這種情況,如何解決這個問題,如何在同一時間

同時播放這是我的代碼實現:

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"remind2" 
              withExtension:@"mp3"]; 
avSound = [[AVAudioPlayer alloc] 
      initWithContentsOfURL:soundURL error:nil]; 
[avSound setDelegate:self]; 

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
[[AVAudioSession sharedInstance] setActive: YES error: nil]; 
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 

[avSound prepareToPlay]; 
[avSound setNumberOfLoops:10]; 
[avSound setVolume:1.0]; 
[avSound play]; 

謝謝!

回答

0

替換該行

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 

本:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil]; 

和我解決我的問題

我花了兩天的時間把正確的問題,對這個問題,我只能找到解決方案,當我問谷歌爲什麼Youtube停止我的音頻流和這個結果搜索幫助我

AVAudioPlayer turns off iPod - how to work around?

0

這是因爲Youtube應用程序還設置屬性「UIBackgroundMode」 plist中的屬性。即使你檢查任何其他音樂應用程序,如gaana,savan等,這將發生在所有的音樂應用程序。

+0

我不這麼認爲,我的iPad上的Youtube應用程序沒有在後臺模式下播放,它立即停止當我推回家按鈕 –

+0

同樣的事情發生在iPhone上嗎? @nghien_rbc –

+0

是的,我已經在iPhone 4S上使用iOS 9.3進行測試並獲得了相同的結果 –