AVFoundation播放視頻實現(xiàn)自動跳過片頭片尾

1.跳過片頭:

KVO監(jiān)聽AVPlayerItem的status,當(dāng)狀態(tài)為AVPlayerItemStatusReadyToPlay時,seek到片頭結(jié)束。

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 ;//片頭結(jié)束時的時間

[self.player seekToTime:time];

[playItem removeObserver:selfforKeyPath:@"status"];//移除監(jiān)聽

}

}

}


2.跳過片尾

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

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

對這個方法傳遞一個時間數(shù)組,player會在播放到指定時間后回調(diào)這個block。

有三個參數(shù):

times :一個由CMTime組成的時間數(shù)組,用于標(biāo)記邊界時間。

queue : 監(jiān)聽的調(diào)度隊列,設(shè)為空時為默認(rèn)為主隊列。

block :監(jiān)聽的回調(diào)代碼塊。block中沒有明確是哪個時間的調(diào)用,需要自己計算。

CMTime time ;//正片結(jié)束時間

NSValue timeValue = [NSValue valueWithCMTime:time];

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

//執(zhí)行相應(yīng)操作,如果是使用的AVQueuePlayer,直接播放下一個資源

[seakSelf.player advanceToNextItem];

}];

}

最后編輯于
?著作權(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)容