使用 AppDelegate,我们响应通知:
applicationWillResignActive和applicationDidBecomeActive
在我们的主程序中,上述调用分别触发了 saveAudioState和restoreAudioState。这些获取 AudioPlayer 的状态,然后在我们从中断中恢复时恢复。这适用于电话中断,但不适用于按下主页按钮。
在 Home 按钮的情况下,currentTime 和 currentAudioItem 的值是无效的。
- (void) saveAudioState {
currentAudioItem = musicPlayer.nowPlayingItem;
currentTime = musicPlayer.currentPlaybackTime;
NSLog(@"Playback state %d", musicPlayer.playbackState);
NSLog(@"Time %f", currentTime);
NSLog(@"Track %@", currentAudioItem);
audioWasPlaying = NO;
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
audioWasPlaying = YES;
[musicPlayer pause];
}
}
- (void) restoreAudioState {
// Restore the now-playing item and its current playback time.
musicPlayer.nowPlayingItem = currentAudioItem;
musicPlayer.currentPlaybackTime = currentTime;
// If the music player was playing, get it playing again.
if (audioWasPlaying && currentAudioItem) {
[musicPlayer play];
}
}
这是 iOS 的一个错误,还是只是事情被破坏的结果?
我已经在 iOS 5.1 和 5.1.1 上进行了测试。