在早期 iOS 開發中,播放本機影片常使用 MPMoviePlayerController。基本流程是先取得影片檔案路徑,建立 NSURL,再以該 URL 初始化播放器。
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"mp4"];
NSURL *url = [NSURL fileURLWithPath:path];
MPMoviePlayerController *movie = [[MPMoviePlayerController alloc] initWithContentURL:url];
movie.controlStyle = MPMovieControlStyleFullscreen;
[movie.view setFrame:self.view.bounds];
[self.view addSubview:movie.view];
[movie play];
若要在播放結束後釋放資源,可註冊 MPMoviePlayerPlaybackDidFinishNotification 通知。收到通知後,移除 observer、把播放器 view 從父視圖移除,再釋放播放器物件。
需要注意的是,MPMoviePlayerController 在後續 iOS 版本中已被 AVPlayer 與 AVPlayerViewController 取代。新專案若要播放影片,建議優先採用 AVFoundation 相關 API。