Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AVPlayer 自定制視頻播放器入門:從加載、播放到進度控制

編輯:關於 Android 程式設計

為什麼需要自定制播放器

AVPlayer 是 iOS 上強大的音視頻播放元件,但若要做出自有風格的播放器,就需要自行管理播放、暫停、進度、靜音與畫面圖層。本文以 AVPlayer 為核心,說明如何建立一個基礎視頻播放器。

建立 AVPlayer 與畫面圖層

AVPlayer 本身只負責播放控制,畫面需要透過 AVPlayerLayer 呈現。因此,通常會同時建立 player 與 playerLayer,並把 playerLayer 加入畫面的 layer 中。

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
NSURL *url = [NSURL URLWithString:urlStr];
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:url options:nil];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
self.player = [AVPlayer playerWithPlayerItem:item];

self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
self.playerLayer.frame = self.layer.bounds;
self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
[self.layer addSublayer:self.playerLayer];

這種寫法比直接用 initWithURL 更具擴展性,因為後續可以對 playerItem 進行監聽,取得狀態、緩衝進度與總時長。

監聽播放狀態與緩衝進度

AVPlayerItem 的 status 可用來判斷是否準備好播放;loadedTimeRanges 則能提供目前緩衝區間。透過 KVO,可以即時更新 UI。

[self.playerItem addObserver:self forKeyPath:@"status" options:0 context:NULL];
[self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:0 context:NULL];

當 status 變成 AVPlayerItemStatusReadyToPlay,表示可以呼叫 play 開始播放。若要取得緩衝長度,可讀取 loadedTimeRanges 的第一個 CMTimeRange,將 start 與 duration 相加。

播放完成通知

影片播放到結尾時,AVPlayerItem 會送出 AVPlayerItemDidPlayToEndTimeNotification。可用來恢復播放按鈕狀態或顯示重播提示。

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackFinished:)
                                             name:AVPlayerItemDidPlayToEndTimeNotification
                                           object:self.player.currentItem];

基本播放控制

從頭播放可搭配 seekToTime 回到起始點,再呼叫 play。暫停可直接呼叫 pause。繼續播放則先 seek 到先前記錄的位置,再播放。

- (void)play {
    [self.player.currentItem seekToTime:CMTimeMakeWithSeconds(0, 1.0)
                        toleranceBefore:kCMTimeZero
                         toleranceAfter:kCMTimeZero];
    [self.player play];
}

- (void)pause {
    self.currentTime = [self playableCurrentTime];
    [self.player pause];
}

- (void)resume {
    [self.player.currentItem seekToTime:CMTimeMakeWithSeconds(self.currentTime, 1.0)
                        toleranceBefore:kCMTimeZero
                         toleranceAfter:kCMTimeZero];
    [self.player play];
}

停止可視為回到開頭並暫停,因此可將播放位置歸零,再呼叫 pause。AVPlayer 的 rate 可用來控制播放速度,1 代表正常速度,0 代表暫停;若需要快轉或慢放,也可嘗試其他數值。

靜音與音量

AVPlayer 的 volume 可控制應用內音量。若要實作靜音切換,建議先保存目前音量,再於取消靜音時恢復。

- (void)playerMute:(BOOL)mute {
    if (mute) {
        [self.player setVolume:0];
    } else {
        [self.player setVolume:self.volumn];
    }
}

需要注意的是,AVPlayer 的 volume 並不等同於系統音量。若系統音量為零,即使將 player volume 設為最大,也不會有聲音。

更新進度條

若希望進度條隨著播放前進,可使用 addPeriodicTimeObserverForInterval。它會以固定時間間隔回呼,讓我們計算目前時間與總時長的比例。

[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0)
                                          queue:dispatch_get_main_queue()
                                     usingBlock:^(CMTime time) {
    float current = CMTimeGetSeconds(time);
    float total = CMTimeGetSeconds([playerItem duration]);
    if (current > 0) {
        [weakSelf.progressBar setValue:(current / total) animated:YES];
    }
}];

釋放觀察者

頁面離開時,必須移除 KVO 與通知,避免記憶體問題或重複回呼。

[self.playerItem removeObserver:self forKeyPath:@"status"];
[self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];

完成這些步驟後,一個具備播放、暫停、繼續、停止、靜音與進度更新能力的基礎視頻播放器便已成形。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved