【问题标题】:AVAudioPlayer cannot play on background when Youtube playing播放 Youtube 时,AVAudioPlayer 无法在后台播放
【发布时间】:2016-08-01 03:45:47
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: ios objective-c avaudioplayer


    【解决方案1】:

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

    【讨论】:

    • 我不这么认为,我 iPad 上的 Youtube 应用程序没有在后台模式下播放,当我按下主页按钮时它立即停止
    • iPhone 也发生了同样的事情? @nghien_rbc
    • 是的,我已经在 iPhone 4S 上使用 iOS 9.3 进行了测试,得到了相同的结果
    【解决方案2】:

    替换这一行

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

    通过这个:

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

    我解决了我的问题

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

    AVAudioPlayer turns off iPod - how to work around?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 2013-07-25
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      相关资源
      最近更新 更多