在 iOS 中播放影片有幾種不同的 API 可選,各有其特性與適用時機。以下依序介紹 AVPlayer、MPMoviePlayerController、MPMoviePlayerViewController 與 AVPlayerViewController。
優缺點:優點是可以完全自訂 UI 進行控制;缺點是它本身只負責播放,沒有內建的控制介面(進度、暫停、播放等按鈕),若要顯示畫面還需借助 AVPlayerLayer 將圖層加入檢視。
遠端影片播放實作:先匯入框架:
#import <AVFoundation/AVFoundation.h>
透過遠端 URL 建立 AVPlayer 並播放(此時只有聲音):
NSURL *remoteURL = [NSURL URLWithString:@"https://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4"]; _player = [AVPlayer playerWithURL:remoteURL]; [self.player play];
若要顯示畫面,需建立 AVPlayerLayer 並加入檢視的 layer:
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player]; layer.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height * 9 / 16); [self.view.layer addSublayer:layer];
優缺點:優點是內建播放控制 UI(進度條、上一個、下一個、暫停),不需手動加入;缺點是不能自訂 UI,且此控制器本身不是視圖控制器,不能直接彈出,只能將其 view 加入其他檢視,播放狀態則透過通知對外溝通。
#import <MediaPlayer/MediaPlayer.h> NSURL *remoteURL = [NSURL URLWithString:@"https://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4"]; _moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:remoteURL]; self.moviePlayer.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height * 9 / 16); self.moviePlayer.controlStyle = MPMovieControlStyleFullscreen; [self.view addSubview:self.moviePlayer.view]; [self.moviePlayer play];
優缺點:優點是內建控制 UI,且本身就是視圖控制器,可以彈出、壓棧,也能手動調整大小加入其他檢視;缺點同樣是不能自訂 UI。
#import <MediaPlayer/MediaPlayer.h>
NSURL *remoteURL = [NSURL URLWithString:@"https://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4"];
_playerVC = [[MPMoviePlayerViewController alloc] initWithContentURL:remoteURL];
[self presentViewController:self.playerVC animated:YES completion:^{
[self.playerVC.moviePlayer play];
}];
在第 2、3 種方案之後,蘋果建議統一改用 AVPlayerViewController。它同樣內建控制 UI,本身是視圖控制器,可彈出、壓棧,也能調整大小加入其他檢視,缺點仍是不便自訂 UI。
#import <AVFoundation/AVFoundation.h> #import <AVKit/AVKit.h> NSURL *remoteUrl = [NSURL URLWithString:@"https://v1.mukewang.com/57de8272-38a2-4cae-b734-ac55ab528aa8/L.mp4"]; AVPlayer *player = [AVPlayer playerWithURL:remoteUrl]; _playerVc = [[AVPlayerViewController alloc] init]; _playerVc.player = player; self.playerVc.view.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height * 9 / 16); [self.view addSubview:self.playerVc.view]; [self.playerVc.player play];
或者直接模態彈出:
[self presentViewController:self.playerVc animated:YES completion:nil];
以上就是 iOS 中幾種影片播放方案的整理。若需高度自訂,可選 AVPlayer;若追求快速上手且系統版本在 iOS 9 以上,建議採用 AVPlayerViewController,希望對你的開發有所幫助。