2014-10-02 217 views
1

在我的應用程序中,我需要播放警報聲。 如果另一個應用程序(如spotify)正在運行,那麼當我運行我的代碼時,它會在警報聲播放時停止播放音樂。 是否有避免這種情況?iOS:在播放其他應用程序時播放聲音

這是我的戲音碼:

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

你怎麼能找出像spotify其他應用程序正在運行? – Unheilig 2014-10-02 09:00:01

+0

當我運行應用程序(通過xcode或不)和spotify在後臺播放時,它停止了來自spotify的聲音... – user3576873 2014-10-03 12:12:57

回答

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]; 

這應該防止將正在播放停止時,你玩你的警報聲音的聲音。

希望這會有所幫助。

+1

非常感謝你!我會盡快測試它,因爲我的服務器現在停機了:( – user3576873 2014-10-06 11:48:38