iOS AVAudioPlayer使其他应用程序的背景音乐停止

时间:2012-07-12 02:35:09

标签: iphone ios

我有一个需要播放声音的运动应用程序。我使用AVAudioPlayer播放声音。 但是当音频开始播放时,来自另一个应用程序(无线电流媒体应用程序)的背景音乐将被关闭。

如何让它不会打断背景音乐?因为我希望用户在锻炼时听到音乐。

谢谢。

5 个答案:

答案 0 :(得分:26)

您可以在使用AVAudioPlayer的地方使用以下代码:

    // Set AudioSession
    NSError *sessionError = nil;
   [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:&sessionError];
   [[AVAudioSession sharedInstance] setActive:YES error:&sessionError];

如果您想设置委托,可以添加以下代码:

   [[AVAudioSession sharedInstance] setDelegate:self];

答案 1 :(得分:6)

在我的情况下,我希望背景音频以较低的音量播放,因为我的应用播放的声音更像是一个警报。我用这个:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // prevents our app from stopping other audio,
    // e.g. music, podcats, etc. that may be playing when launched
    // our audio will be played at a higher volume
    // and the background audio will "duck" until done
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryMultiRoute 
                                     withOptions:AVAudioSessionCategoryOptionDuckOthers
                                           error:nil];
}

答案 2 :(得分:5)

基于SujithPt的答案这里的答案与swift相同:

AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)

答案 3 :(得分:1)

对于Swift 2.2,在播放或准备播放之前将其添加到任何位置:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)

答案 4 :(得分:0)

对于Swift 4.2

import AVFoundation

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    do {
        try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default, options: AVAudioSession.CategoryOptions.mixWithOthers)
    } catch let error {
        print(error.localizedDescription)
    }

    return true
}
相关问题