Stefan Kendall
Stefan Kendall

Reputation: 67802

Playing a sound in iOS pauses background music

How do I play a sound in iOS without pausing the background music?

I have this:

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

And yet any background music is stopped. What am I missing?

I also tried this, to no avail:

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

Upvotes: 2

Views: 1757

Answers (1)

sooper
sooper

Reputation: 6039

You need to set the appropriate audio session, something like this:

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

Upvotes: 2

Related Questions