2012-11-15 96 views
2

如何在不暂停背景音乐的情况下在iOS中播放声音?在iOS中播放声音会暂停背景音乐

我有这样的:

NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"wav"]; 
NSURL *url = [NSURL URLWithString:soundPath]; 

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; 
AVAudioPlayer *audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: url error:nil]; 
audioPlayer.numberOfLoops = 0; 
[audioPlayer play]; 

而且还没有任何背景音乐停止。我错过了什么?

我也试过了,没有用:

- (void)alarm:(CDVInvokedUrlCommand *)command { 
    [self setupAudioSession]; 
    NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"alert" ofType:@"wav"]; 
    NSURL *url = [NSURL URLWithString:soundPath]; 

    AVPlayer *audioPlayer = [[AVPlayer alloc] initWithURL: url]; 
    [audioPlayer play]; 
} 

- (void)setupAudioSession { 
    AudioSessionInitialize(NULL,NULL,NULL,NULL); 

    OSStatus activationResult = 0; 
    activationResult   = AudioSessionSetActive(true); 

    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; 

    AudioSessionSetProperty 
    (
    kAudioSessionProperty_AudioCategory, 
    sizeof(sessionCategory), 
    &sessionCategory 
    ); 

    OSStatus propertySetError = 0; 
    UInt32 allowMixing  = true; 

    propertySetError = AudioSessionSetProperty 
    (
    kAudioSessionProperty_OverrideCategoryMixWithOthers, 
    sizeof(allowMixing), 
    &allowMixing 
    ); 
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil]; 
} 

回答

2

您需要设置相应的音频会议,这样的事情:

AudioSessionInitialize(NULL,NULL,NULL,NULL); 

OSStatus activationResult = 0; 
activationResult   = AudioSessionSetActive(true); 

UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; 

AudioSessionSetProperty 
(
    kAudioSessionProperty_AudioCategory, 
    sizeof(sessionCategory), 
    &sessionCategory 
); 

OSStatus propertySetError = 0; 
UInt32 allowMixing  = true; 

propertySetError = AudioSessionSetProperty 
(
    kAudioSessionProperty_OverrideCategoryMixWithOthers, 
    sizeof(allowMixing), 
    &allowMixing 
); 
+0

我列出的代码之前跑了这一点,同样的结果。 –

+0

奇怪,在使用'AVPlayer'时它似乎对我很好。 AVPlayer是你的选择吗?可能你可以尝试一下,至少看看代码是否正在工作(它应该)。 – sooper

+0

我更新了我的示例,并尝试了一些内容,并且停止了背景声音。 –