用 MediaPlayer Framework 中的 MPMoviePlayerController,幾行程式碼就能做出一個可播放 HLS(M3U8)串流的播放器。這篇文章示範最精簡的版本。
#import <UIKit/UIKit.h> @class PlayerViewController; @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) PlayerViewController *vc; @end
#import "AppDelegate.h"
#import "PlayerViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.vc = [[PlayerViewController alloc] initWithNibName:nil bundle:nil];
self.window.rootViewController = self.vc;
[self.window makeKeyAndVisible];
return YES;
}
// 其餘預設方法略
@end
#import <UIKit/UIKit.h> @interface PlayerViewController : UIViewController @end
在 viewDidLoad 中建立播放器並指定串流位址。這裡把 URL 寫死是為了示範:
#import "PlayerViewController.h"
#import <MediaPlayer/MediaPlayer.h>
@interface PlayerViewController ()
@property (strong, nonatomic) MPMoviePlayerController *streamPlayer;
@end
@implementation PlayerViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *streamURL = [NSURL URLWithString:
@"https://www.thumbafon.com/code_examples/video/segment_example/prog_index.m3u8"];
self.streamPlayer = [[MPMoviePlayerController alloc] initWithContentURL:streamURL];
[self.streamPlayer.view setFrame:self.view.bounds];
self.streamPlayer.controlStyle = MPMovieControlStyleEmbedded;
[self.view addSubview:self.streamPlayer.view];
[self.streamPlayer play];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
MPMovieControlStyleEmbedded 表示控制列內嵌在 view 中,適合自行排版;Fullscreen 則是滿版播放;None 則完全隱藏控制項。MPMoviePlayerLoadStateDidChangeNotification、MPMoviePlayerPlaybackDidFinishNotification 等通知取得,並用 loadState 與 playbackState 判斷,比定時輪詢準確得多。applicationDidEnterBackground: 中呼叫暫停,回前景時再由使用者決定是否續播,避免資源浪費。MPMoviePlayerController 自 iOS 9 起已被標記為 deprecated,新專案請改用 AVPlayer 搭配 AVPlayerLayer(或 AVPlayerViewController)。M3U8 播放對 AVPlayer 而言只是換一個 URL,寫法幾乎一樣簡單:
AVPlayerItem *item = [AVPlayerItem playerItemWithURL:streamURL]; self.player = [AVPlayer playerWithPlayerItem:item]; AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:self.player]; layer.frame = self.view.bounds; [self.view.layer addSublayer:layer]; [self.player play];
改用 AVPlayer 的好處是:控制更細緻、與 AVPlayerViewController 整合後可直接得到完整播放介面,並且能監聽 AVPlayerItemDidPlayToEndTimeNotification 與 timeControlStatus 來掌握播放狀態。