整理一下 iOS 上播放影片的兩套做法。以下範例使用放在 App bundle 內的本地檔,若要播放網路影片,把 URL 換掉即可。
先匯入 MediaPlayer 框架。這套 API 提供兩種播放元件。
1. 帶界面的 MPMoviePlayerViewController——本身就是一個 view controller,直接 present 出來即可:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"];
MPMoviePlayerViewController *mpvc =
[[MPMoviePlayerViewController alloc] initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:mpvc];2. 不帶界面的 MPMoviePlayerController——名字裡沒有 View,指的是它不像上一個那樣自帶完整控制器,但它仍有一個 view 屬性需要自行安置:
NSURL *url = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"];
MPMoviePlayerController *mpc =
[[MPMoviePlayerController alloc] initWithContentURL:url];
// frame 依版面需求自行調整
mpc.view.frame = CGRectMake(40, 50, 200, 200);
// 控制列樣式
mpc.controlStyle = MPMovieControlStyleEmbedded;
[self.view addSubview:mpc.view];
[mpc play];
// 需強引用,否則播放器等級被回收
self.mpc = mpc;3. 透過通知實作自動播放下一個
// 註冊播放結束通知
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playbackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:nil];- (void)playbackDidFinish:(NSNotification *)notification {
NSLog(@"%@", notification.userInfo);
MPMovieFinishReason reason =
[notification.userInfo[MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
// 只有正常播完才接下一首,使用者中途跳出則不觸發
if (reason == MPMovieFinishReasonPlaybackEnded) {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"next" withExtension:@"mp4"];
self.mpc.contentURL = url;
[self.mpc play];
}
}iOS 9 新增 AVKit,提供 AVPlayerViewController。使用時必須同時匯入 AVKit 與 AVFoundation——因為這個控制器本身不具備播放能力,必須指派一個 AVPlayer 給它。
- (IBAction)play:(id)sender {
AVPlayerViewController *playerVc = [[AVPlayerViewController alloc] init];
// AVPlayer 定義在 AVFoundation 中,因此該框架不可少
NSURL *url = [[NSBundle mainBundle] URLForResource:@"movie" withExtension:@"mp4"];
playerVc.player = [AVPlayer playerWithURL:url];
[self presentViewController:playerVc animated:YES completion:^{
[playerVc.player play];
}];
playerVc.delegate = self;
}補充:畫中畫(PiP)相關的委派方法。注意畫中畫目前僅部分 iPad 機型支援。
- (void)playerViewControllerWillStartPictureInPicture:(AVPlayerViewController *)pvc {
NSLog(@"即將開始畫中畫");
}
- (void)playerViewControllerDidStartPictureInPicture:(AVPlayerViewController *)pvc {
NSLog(@"已開始畫中畫");
}
- (void)playerViewControllerWillStopPictureInPicture:(AVPlayerViewController *)pvc {
NSLog(@"即將停止畫中畫");
}
- (void)playerViewControllerDidStopPictureInPicture:(AVPlayerViewController *)pvc {
NSLog(@"畫中畫已停止");
}
- (void)playerViewController:(AVPlayerViewController *)pvc
failedToStartPictureInPictureWithError:(NSError *)error {
NSLog(@"開啟畫中畫失敗:%@", error);
}
// 播放器和 App 以 modal 形式呈現時,進入畫中畫是否自動關閉該控制器;預設為 YES
- (BOOL)playerViewControllerShouldAutomaticallyDismissAtPictureInPictureStart:
(AVPlayerViewController *)pvc {
return NO;
}選擇建議:新專案直接用 AVPlayerViewController。MediaPlayer 那套在 iOS 9 起已被標記為棄用,只適合維護舊程式碼時參考。