如何在不停顿背景音乐的情况下在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];
}
答案 0 :(得分: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
);