【问题标题】:iOS: playing sound while other apps are playingiOS:在其他应用程序播放时播放声音
【发布时间】:2014-10-02 07:34:40
【问题描述】:

在我的应用程序中,我需要播放警报声音。 如果另一个应用程序(如Spotify)正在运行,当我运行我的代码时,它会在播放警报声时停止音乐播放。 有没有办法避免这种情况?

这是我的播放声音代码:

- (void)playSendSound
{
    NSString* path;
    NSURL* url;

    path = [[NSBundle mainBundle] pathForResource:@"soundBit" ofType:@"aif"];
    url = [NSURL fileURLWithPath:path];
    player = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    [player play];
}

【问题讨论】:

  • 您如何知道其他应用(如 spotify)正在运行?
  • 当我运行应用程序(通过或不通过 xcode)并且 spotify 在后台播放时,它停止了来自 spotify 的声音...

标签: ios audio avaudioplayer


【解决方案1】:

您正在使用AVAudioPlayer 播放警报声音,并确保它会停止正在播放的任何音乐。

修改你的代码如下:

NSString* path;
NSURL* url;

path = [[NSBundle mainBundle] pathForResource:@"soundBit" ofType:@"aif"];
url = [NSURL fileURLWithPath:path];
player = nil;
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&error];
[player play];

这应该可以防止正在播放的声音在您播放警报声音时停止。

希望这会有所帮助。

【讨论】:

  • 非常感谢!我会尽快测试它,因为我的服务器现在已经关闭:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多