繁体   English   中英

在 iOS 中播放声音会暂停背景音乐

[英]Playing a sound in iOS pauses background music

如何在不暂停背景音乐的情况下在 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];
}

您需要设置适当的音频会话,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM