Search code examples
iosobjective-cavaudioplayer

AVAudioPlayer cannot play on background when Youtube playing


I make an alarm feature for my app, at the time I setup for alarm fire I can play a music track with AVAudioPlayer, it worked well on background mode. But if at this time I opening Youtube app and playing a video then the AVAudioPlayer not work.

Please tell me why this happen and how to resolve this issue, how to play both at the same time

This is code I implement:

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"remind2"
                                          withExtension:@"mp3"];
avSound = [[AVAudioPlayer alloc]
            initWithContentsOfURL:soundURL error:nil];
[avSound setDelegate:self];

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

[avSound prepareToPlay];
[avSound setNumberOfLoops:10];
[avSound setVolume:1.0];
[avSound play];

Thanks!


Solution

  • Replace this line

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    

    by this:

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
    

    and I resolved my problem

    It takes me two days to put the right questions to this problem, I only find the solution when i ask Google why Youtube stop my audio stream and this result search help me

    AVAudioPlayer turns off iPod - how to work around?