MPMoviePlayerViewController已經實現了一些通知的監聽並對MPMoviePlayerController實現了一些控制,比如:
1. 監聽UIApplicationDidEnterBackgroundNotification通知,調用[movieplayer stop],播放器停止。
2. 監聽MPMoviePlayerPlaybackDidFinishNotification(調用stop方法或視頻播放結束時發送通知)通知,調用dismiss方法移除自身。
需求1:app中一個課程包含若干個章節,所以每次播放完一個章節後要求直接加載播放下一個課程。
遇到問題:由於MPMoviePlayerViewController監聽了MPMoviePlayerPlaybackDidFinishNotification通知,當一個視頻播放完畢,它會在監聽方法中 調用dismissMoviePlayerViewControllerAnimated方法,播放器視圖就直接移除了。
解決方法:
// self爲MPMoviePlayerViewController的一個實例對象。
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
需求2: app進入後臺時播放器暫停,回到應用時繼續播放
遇到問題:由於MPMoviePlayerViewController監聽了UIApplicationDidEnterBackgroundNotification通知,當進入後臺時,調用stop方法,隨後接 收到MPMoviePlayerPlaybackDidFinishNotification通知,調用dismiss方法移除自身視圖。
解決方法:移除MPMoviePlayerViewController對UIApplicationDidEnterBackgroundNotification和MPMoviePlayerPlaybackDidFinishNotification 通知的監聽,並實現自己的監聽方法
// UIApplicationDidEnterBackgroundNotification通知
- (void)appEnterBackground:(NSNotification*)notice {
// 進入後臺時記錄當前播放時間 overlay_flags.playTimeWhenEnterBackground = _player.currentPlaybackTime; [_player pause]; }
// UIApplicationWillEnterForegroundNotification通知
- (void)appEnterForeground:(NSNotification*)notice
{
// 設置播放速率爲正常速度,設置當前播放時間爲進入後臺時的時間
[_player setCurrentPlaybackRate:1.0];
[_player setCurrentPlaybackTime:overlay_flags.playTimeWhenEnterBackground];
}