Youtube 播放时 AVAudioPlayer 无法在后台播放

AVAudioPlayer cannot play on background when Youtube playing

我为我的应用程序制作了一个闹钟功能,当我设置闹钟时,我可以用 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];

谢谢!

这是因为 Youtube 应用程序还在 plist 中设置了 属性 "UIBackgroundMode" 属性。即使您检查任何其他音乐应用程序,如 gaana、savan 等,这也会在所有音乐应用程序中发生。

替换此行

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

通过这个:

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

我解决了我的问题

我花了两天时间才对这个问题提出正确的问题,当我问 Google 为什么 Youtube 停止我的音频流时我才找到解决方案,这个搜索结果对我有帮助

AVAudioPlayer turns off iPod - how to work around?