首先建一個基於視圖的的項目命名為PlayVideo,並給項目中的Frameworks添加MediaPlayer.framework,:
加進去了以後,再給檔案裡添加一個視頻檔案video.m4v,注意副檔名,我先開始添加的視頻檔案的副檔名為mp4,結果一直播放的時候就是不播,所以我把視頻轉換成m4v副檔名就行了!
接下來是在PlayViewContrller.h檔案中添加屬性:
MPMoviePlayerController *player;//控制視頻播放
然後是PlayViewController.m檔案中添加代碼實現:
[cpp] - (void)viewDidLoad
{
//擷取視頻檔案的名稱
NSString *url=[[NSBundle mainBundle]pathForResource:@"video" ofType:@"m4v"];
//初始化player,檔案是video.m4v
player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
//然後,您使用的NSNotificationCenter類註冊通知,這樣當影片完成播放(即結束)的時候調用movieFinishedCallback:方法;
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification object:player];
//設定視頻視圖的大小
player.view.frame = CGRectMake(10, 10, 300, 300);
//添加控制項
[self.view addSubview:player.view];
//播放影片
[player play];
[super viewDidLoad];
}
//電影停止播放時,你應該登出的通知,刪除的影片,然後釋放播放對象:
-(void)movieFinishedCallback:(NSNotification*) aNotification {
MPMoviePlayerController *moviePlayer = [aNotification object];
//登出通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
//刪除影片
[moviePlayer.view removeFromSuperview];
//釋放
[player release];
}
- (void)viewDidLoad
{
//擷取視頻檔案的名稱
NSString *url=[[NSBundle mainBundle]pathForResource:@"video" ofType:@"m4v"];
//初始化player,檔案是video.m4v
player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
//然後,您使用的NSNotificationCenter類註冊通知,這樣當影片完成播放(即結束)的時候調用movieFinishedCallback:方法;
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(movieFinishedCallback:)
name:MPMoviePlayerPlaybackDidFinishNotification object:player];
//設定視頻視圖的大小
player.view.frame = CGRectMake(10, 10, 300, 300);
//添加控制項
[self.view addSubview:player.view];
//播放影片
[player play];
[super viewDidLoad];
}
//電影停止播放時,你應該登出的通知,刪除的影片,然後釋放播放對象:
-(void)movieFinishedCallback:(NSNotification*) aNotification {
MPMoviePlayerController *moviePlayer = [aNotification object];
//登出通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayer];
//刪除影片
[moviePlayer.view removeFromSuperview];
//釋放
[player release];
}
實現效果:
:
點擊右下角放大表徵圖
雙擊螢幕變成全屏:
點擊Done按鈕恢複原狀!!!
ok!實現!本部落格是我自己的練習,有好多地方沒有講太清楚,還請諒解!
摘自 任海麗(3G/移動開發)