使用 MediaPlayer 播放影片之前,記得先匯入對應框架:
#import <MediaPlayer/MediaPlayer.h>
並在專案設定中加入 MediaPlayer.framework。
- (void)openmovie
{
MPMoviePlayerViewController *movie = [[MPMoviePlayerViewController alloc]
initWithContentURL:[NSURL URLWithString:@"視頻網絡地址"]];
[movie.moviePlayer prepareToPlay];
[self presentMoviePlayerViewControllerAnimated:movie];
[movie.moviePlayer setControlStyle:MPMovieControlStyleFullscreen];
[movie.view setBackgroundColor:[UIColor clearColor]];
[movie.view setFrame:self.view.bounds];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:movie.moviePlayer];
}
- (void)movieFinishedCallback:(NSNotification *)notify
{
// 影片播完,或 fullscreen 模式下 Done 按鈕被點擊時會收到此通知
MPMoviePlayerController *theMovie = [notify object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:theMovie];
[self dismissMoviePlayerViewControllerAnimated:YES];
}
- (void)openmovie
{
NSString *url = [[NSBundle mainBundle] pathForResource:@"IMG_0322" ofType:@"mp4"];
MPMoviePlayerViewController *playerViewController =
[[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:[playerViewController moviePlayer]];
[self.view addSubview:playerViewController.view];
MPMoviePlayerController *player = [playerViewController moviePlayer];
[player play];
}
- (void)movieFinishedCallback:(NSNotification *)aNotification
{
MPMoviePlayerController *player = [aNotification object];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
[player stop];
[player.view removeFromSuperview];
}
播放網路與本機影片的唯一差別在於 URL 的建立方式:網路來源用 URLWithString,本機檔案用 fileURLWithPath。
無論哪一種,一定要註冊 MPMoviePlayerPlaybackDidFinishNotification,並在回呼中移除 observer,否則重複播放會累積多個監聽而導致崩潰或重複觸發。
另外要提醒的是,MPMoviePlayerController 與 MPMoviePlayerViewController 這一整組 API 從 iOS 9 起已被標記為 deprecated,新專案建議改用 AVPlayer 搭配 AVPlayerViewController,才能拿到更完整的播放控制與 AirPlay 支援。