幾行代碼略看iOS的影片播放: MediaPlayer 和 AVPlayer

在iOS開發(fā)上,如果遇到需要播放影片,如開機動畫,我們很習慣地會使用MediaPlayer來播放影片,因為很方便使用,所以就一直使用下去。但是隨著客戶的要求越來越嚴苛,尤其是過場動畫或互動效果上的表現(xiàn)。所以如果在一些動畫中還攜帶影片一起運算,那勢必機器會跑不動。所以在iOS 4之后,我們可以使用AVPlayer這個類別來進行更細微的操作。

注意:

  • MediaPlayer的影片是放在UIView 裡面,而AVPlayer是放在AVPlayerLayer里面,AVPlayerLayer是CALayer 的子類。
  • 使用MediaPlayer前,要記得導入
    MediaPlayer.framework及#import <MediaPlayer/MediaPlayer.h>
  • 使用AVPlayer前,要記得導入
    AVFoundation.frameworkk及#import <AVFoundation/AVFoundation.h>

先簡單的看下本地視頻的處理,請參考以下范例:

使用MediaPlayer來播放影片

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"backspace" ofType:@"mov"];  
NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];  
  
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:sourceMovieURL];  
moviePlayer.view.frame=CGRectMake(0, 0, 1024, 768);  
moviePlayer.controlStyle=MPMovieControlStyleNone;  
  
// Play the movie!  
[self.view addSubview:moviePlayer.view];  

使用AVPlayer來播放影片



NSString *filePath = [[NSBundle mainBundle] pathForResource:@"backspace" ofType:@"mov"];  
NSURL *sourceMovieURL = [NSURL fileURLWithPath:filePath];  
  
AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:sourceMovieURL options:nil];  
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];  
AVPlayer *player = [AVPlayer playerWithPlayerItem:playerItem];  
AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];  
playerLayer.frame = self.view.layer.bounds;  
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;  
  
[self.view.layer addSublayer:playerLayer];  
[player play];  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容