iOS中 MPMoviePlayer 實現視頻音頻播放 作者:韓俊強
ios播放視頻檔案一般使用 MPMoviePlayerViewController 和 MPMoviePlayerController。前者是一個view,後者是個Controller。區別就是 MPMoviePlayerViewController裡麵包含了一個MPMoviePlayerController
注意:MPMoviePlayerViewController 必須 presentMoviePlayerViewControllerAnimated方式添加,否則Done按鈕是不會響應通知MPMoviePlayerPlaybackDidFinishNotification事件的;
首先要包含 #import 標頭檔和MediaPlayer.framework。
MPMovieControlModeDefault 顯示播放 / 暫停、音量和時間控制
MPMovieControlModeVolumeOnly 只顯示音量控制
MPMovieControlModeHidden 沒有控制器
你可以使用下列寬高比值:
MPMovieScallingModeNone 不做任何縮放
MPMovieScallingModeAspectFit 適應螢幕大小,保持寬高比
MPMovieScallingModeAspectFill 適應螢幕大小,保持寬高比,可裁剪
MPMovieScallingModeFill 充滿螢幕,不保持寬高比
//通知
MPMoviePlayerContentPreloadDidFinishNotification 當電影播放器結束對內容的預先載入後發出。因為內容可以在僅載入了一部分的情況下播放,所以這個通知可能在已經播放後才發出。
MPMoviePlayerScallingModeDidChangedNotification 當使用者改變了電影的縮放模式後發出。使用者可以點觸縮放表徵圖,在全屏播放和視窗播放之間切換。
MPMoviePlayerPlaybackDidFinishNotification 當電影播放完畢或者使用者按下了 Done 按鈕後發出
===============================================================================
需要引進的架構:MediaPlayer.framework
第一步:引進架構設定屬性
#import RootViewController.h#import @interface RootViewController ()@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;@end@implementation RootViewController
調用:
- (void)viewDidLoad { [super viewDidLoad]; // 5.調用播放器 //播放網路視頻 NSString *urlString = @http://video.szzhangchu.com/qiaokeliruanxinbudingA.mp4; //播放本地視圖,找到檔案的路徑 // NSString *urlStr = [[NSBundle mainBundle] pathForResource:@優酷網-唐豆豆搖一搖慘被騙.mp4 ofType:nil]; [self createMPPlayerController:urlString]; }
第二步:建立播放器
- (void)createMPPlayerController:(NSString *)string{ // 1.初始化播放器 //準備網址// NSURL *urlString = [NSURL fileURLWithPath:fileNamePath]; NSURL *urlString = [NSURL URLWithString:string]; //初始化播放器 self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:urlString]; //準備播放// [_moviePlayer prepareToPlay]; //設定moviePlayer的frame _moviePlayer.view.frame = self.view.frame; //添加到父視圖 [self.view addSubview:_moviePlayer.view]; // 2.配置屬性 //是否自動播放,預設是NO _moviePlayer.shouldAutoplay = YES; //設定播放器的樣式 [_moviePlayer setControlStyle:(MPMovieControlStyleFullscreen)]; //開始播放 [_moviePlayer play]; // 3.註冊通知 //註冊通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinshed:) name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; }
第三步:實現通知方法
// 4.實現通知中的方法- (void)movieFinshed:(NSNotification *)sender{ //取出通知中樞的moviePlayer MPMoviePlayerController *movie = [sender object]; //移除觀察者 [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; //將movie移出父視圖 [movie.view removeFromSuperview]; }
最終效果: