Playing music at back ground: AVAudioSessionInterruptionNotification not fired

五迷三道 提交于 2019-12-06 21:11:01

问题


My app is playing in background well. Pause and play also works well even my app is background using the methods registered for AVAudioSessionInterruptionNotification.

The problem arrives steps for the scenario:

  1. Launch my app -> goes background music from my app playing well
  2. launch apple's music app and play. AVAudioSessionInterruptionNotification fired.
  3. When i pause the music app or kill the music app. AVAudioSessionInterruptionNotification doesn't get fired

Code: I am doing this in appdelegate. didfinishlaunching

NSError *sessionError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
[[AVAudioSession sharedInstance] setActive:YES error: nil];

self.player = [[AVQueuePlayer alloc] initWithURL:[NSURL URLWithString:@"http://someurl.com:8040/;stream.mp3"]];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];




- (void) onAudioSessionEvent: (NSNotification *) notification
{
    //Check the type of notification, especially if you are sending multiple AVAudioSession events here
    NSLog(@"Interruption notification name %@", notification.name);

    if ([notification.name isEqualToString:AVAudioSessionInterruptionNotification]) {
        NSLog(@"Interruption notification received %@!", notification);

        //Check to see if it was a Begin interruption
        if ([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeBegan]]) {
            NSLog(@"Interruption began!");

        } else if([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]){
            NSLog(@"Interruption ended!");
            //Resume your audio
            NSLog(@"Player status %i", self.player.status);
            // Resume playing the audio.
            [self.player play];

        }
    }
}

回答1:


I had similar problem with interrupts. iOS: Siri not available does not return AVAudioSessionInterruptionOptionShouldResume

Ended up using applicationWillResignActive and applicationDidBecomeActive instead.




回答2:


There is Property of your AVCaptureSession instance: @property(nonatomic) BOOL usesApplicationAudioSession

It is YES by default just set it to NO, and will works fine.




回答3:


Try to add object:session

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];



来源:https://stackoverflow.com/questions/22400345/playing-music-at-back-ground-avaudiosessioninterruptionnotification-not-fired

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!