ios - iOS:在播放其他应用程序时播放声音

标签 ios audio avaudioplayer

在我的应用程序中,我需要播放警报声音。
如果另一个应用程序(例如spotify)正在运行,则当我运行代码时,只要播放警报声音,它都会停止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];
}

最佳答案

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

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

希望这可以帮助。

关于ios - iOS:在播放其他应用程序时播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26156207/

相关文章:

ios - Mozharovsky 的 CVCalendar 日期不显示

ios - 纵向 View 在 swift 中提供与横向模式相同的宽度

javascript - 使用 flash 或 html5 捕获音频输入

php - 使用 ffmpeg 转换音频文件并保留专辑插图

iphone - 如何在通话期间以编程方式在 iPhone 的两个扬声器上播放声音

ios - 声音播放完毕后,AVAudioPlayer实例会怎样?

ios - 在 prepareForSegue 上为 Popover Segue : strange behavior in iOS 5 传递数据

ios - 如何同时支持纵向和横向模式 - XIB 的可重用 View

ios - iPhone 7 Plus AVPlayer 周围有边框(白色颜色不匹配)

iphone - 最佳音频播放器