问题
I'm writing a radio app for both iPhone and iPad and am running into some weird behaviour when handling pausing and playing the audio with interruptions. I'm using the AVAudioSessionDelegate methods beginInterruption
and endInterruption
to respectively pause
and play
the AVPlayer. Below is the relevant play
code.
Now, the following situations seem to happen consistently:
- On iPad: If I force an interruption (Facetime call),
beginInterruption
is called as expected and playback stops. If the interruption stops,endInterruption
is called as expected, and the playback resumes as expected. - On iPhone: Pressing the play and pause button, triggers
pause
andplay
exactly the same asbeginInterruption
andendInterruption
would. Playback behaves as expected. - On iPhone: Forcing an interruption (by calling the phone), calls
endInterruption
as expected and playback pauses as expected. However, when the interruption is finished,beginInterruption
is called as expected,play
is called as expected, it actually reaches and executes the[self.player play]
line, but playback does not resume! I hear nothing.
Situation 3 above is extremely weird, so I'm wondering if I may have overlooked something. Any ideas?
Play
code
- (void)play {
NSError* error = nil;
AVKeyValueStatus keyStatus = [currentAsset statusOfValueForKey:@"tracks" error:&error];
if(error){
DLog(@"Error %@", [error localizedDescription]);
}
else {
DLog(@"Current Key Status: %i", keyStatus);
if(keyStatus == AVKeyValueStatusLoaded){
DLog(@"Continue playing source: %@", self.source);
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
if (error) {
DLog(@"Error during play while setting AVAudioSessionCategory: %@", [error localizedDescription]);
}
[[AVAudioSession sharedInstance] setActive:YES error:&error];
if (error) {
DLog(@"Error during play while setting AVAudioSessionCategory: %@", [error localizedDescription]);
}
[[AVAudioSession sharedInstance] setDelegate:self];
if(backgroundTaskID != UIBackgroundTaskInvalid){
[[UIApplication sharedApplication] endBackgroundTask:backgroundTaskID];
}
backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
[self.player play];
[self setStatus:kNPOMediaPlayerStatusPlaying];
}
else {
DLog(@"PlaySource: %@", self.source);
[self playSource:self.source];
}
}}
回答1:
I had the same issue. Issue disappeared after I implemented remote control event handling. I called [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
when starting playback.
回答2:
It turns out that this is a known bug in iOS, which requires some careful work-arounds in the applicationDidBecomeActive to handle beginInterruption. Sadly, I couldn't figure out another solution.
来源:https://stackoverflow.com/questions/12461691/avplayer-doesnt-resume-playback-on-endinterruption-on-iphone-but-does-so-on-ipa