iOS:在播放其他应用时播放声音

时间:2014-10-02 07:34:40

标签: ios audio avaudioplayer

在我的应用程序中,我需要播放警报声。 如果另一个应用程序(如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];
}

1 个答案:

答案 0 :(得分:0)

您正在使用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];

这可以防止播放提示音时播放的声音停止。

希望这有帮助。