AVFoundation播放視頻實現自動跳過片頭片尾

1.跳過片頭:

KVO監聽AVPlayerItem的status,當狀態為AVPlayerItemStatusReadyToPlay時,seek到片頭結束。

NSURL*url = ;

AVAsset*asset = [AVAsset assetWithURL:url];

AVPlayerItem*playItem = [AVPlayerItem playerItemWithAsset:asset];

[playItem addObserver:self forKeyPath:@"status"options:0context:nil];

- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void*)context{

if([keyPath isEqualToString:@"status"]) {

AVPlayerItem*playItem = object;

if(playItem.status==AVPlayerItemStatusReadyToPlay){

CMTime time ;//片頭結束時的時間

[self.player seekToTime:time];

[playItem removeObserver:selfforKeyPath:@"status"];//移除監聽

}

}

}


2.跳過片尾

跳過片尾需要用到AVPlayer的一個邊界時間監聽的方法:

-(id)addBoundaryTimeObserverForTimes:(NSArray *)times queue:(nullable dispatch_queue_t)queue usingBlock:(void(^)(void))block;

對這個方法傳遞一個時間數組,player會在播放到指定時間后回調這個block。

有三個參數:

times :一個由CMTime組成的時間數組,用于標記邊界時間。

queue : 監聽的調度隊列,設為空時為默認為主隊列。

block :監聽的回調代碼塊。block中沒有明確是哪個時間的調用,需要自己計算。

CMTime time ;//正片結束時間

NSValue timeValue = [NSValue valueWithCMTime:time];

[self.player addBoundaryTimeObserverForTimes:@[timeValue]queue:nil usingBlock:^{

//執行相應操作,如果是使用的AVQueuePlayer,直接播放下一個資源

[seakSelf.player advanceToNextItem];

}];

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容