2012-07-12 137 views
14

我有一個需要播放聲音的練習應用程序。我使用AVAudioPlayer播放聲音。 但是當音頻開始播放時,來自另一個應用程序(廣播流應用程序)的背景音樂被關閉。iOS AVAudioPlayer讓其他應用程序的背景音樂停止

我該如何讓它不中斷背景音樂?因爲我希望用戶在鍛鍊時聽音樂。

謝謝。

+1

的[iPhone AVAudioPlayer停止背景音樂]可能重複(http://stackoverflow.com/questions/1672602/iphone-avaudioplayer-stopping-background-music) – benzado 2012-07-12 02:38:26

+0

你需要使用不同類型的音頻會話 – bkbeachlabs 2012-07-12 03:00:10

回答

26

您可以使用在您使用AVAudioPlayer下面的代碼:基於SujithPt的答案在這裏

[[AVAudioSession sharedInstance] setDelegate:self]; 
+0

你是否真的需要設置代表。設置類別應該足夠了。 – 2013-01-08 12:12:09

+0

我測試了代碼,只需要調用setCategory就可以了。相應地更改了示例代碼。 – 2013-01-08 13:12:55

+0

當來自其他應用程序的音頻在後臺播放時,我的應用程序會崩潰,原因是:'所需條件爲false:_engine-> IsRunning()'。這解決了這個問題。 – vikzilla 2015-09-07 07:26:21

5

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

如果您想設置一個委託,您可以添加這行代碼是在快速同樣的事情:

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

在我的情況下,我想背景音頻播放音量較低,因爲我的應用播放的聲音更像是一個警報。我用這個:

- (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]; 
} 
1

對於雨燕2.2,添加這個你玩之前的任何地方或preparetoplay:

_ = try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient) 
相關問題