美文网首页
iOS 顺序播放多个视频

iOS 顺序播放多个视频

作者: 十重火 | 来源:发表于2019-08-06 09:32 被阅读0次

1.使用AVPlayer

[self.player replaceCurrentItemWithPlayerItem:curItem];

2.使用AVQueuePlayer

AVQueuePlayer *player = [AVQueuePlayer queuePlayerWithItems:@[item1,item2]];

3.使用AVMutableComposition 组合多个视频

-(AVMutableComposition*)getVideoComposition:(NSArray*)array {
    AVMutableComposition* mixComposition = [AVMutableComposition composition];
    AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    Float64 tmpDuration =0.0f;
    NSMutableArray *assetArray = [NSMutableArray new];
    for (NSInteger i=0; i<array.count; i++)
    {
        
        AVURLAsset *videoAsset = [[AVURLAsset alloc]initWithURL:array[i] options:nil];
        [assetArray addObject:videoAsset];
    }
    for (NSInteger i=0; i<assetArray.count; i++) {
        AVURLAsset *videoAsset = [assetArray objectAtIndex:i];
        CMTimeRange video_timeRange = CMTimeRangeMake(kCMTimeZero,videoAsset.duration);
    
        NSError *error;
        
        NSArray *tracks = [videoAsset tracksWithMediaType:AVMediaTypeVideo];
        
        AVAssetTrack *videoTrack = [tracks objectAtIndex:0];
        
        [compositionVideoTrack insertTimeRange:video_timeRange ofTrack:videoTrack atTime:CMTimeMakeWithSeconds(tmpDuration, 0) error:&error];
        
        
        NSArray *audios = [videoAsset tracksWithMediaType:AVMediaTypeAudio];
        
        if(audios.count > 0) {
            [compositionAudioTrack insertTimeRange:video_timeRange ofTrack:[audios objectAtIndex:0] atTime:CMTimeMakeWithSeconds(tmpDuration, 0) error:&error];
            
        }else {
            
            [compositionAudioTrack insertEmptyTimeRange:CMTimeRangeMake(CMTimeMake(tmpDuration, 1000), videoAsset.duration)];
        }
    
        [compositionVideoTrack setPreferredTransform:videoTrack.preferredTransform];
        tmpDuration += CMTimeGetSeconds(videoAsset.duration);
        
    }
 
    return mixComposition;
}

AVMutableComposition *composition = [self getVideoComposition:array];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:[composition copy]];
AVPlayer *player =[AVPlayer playerWithPlayerItem:item];

相关文章

网友评论

      本文标题:iOS 顺序播放多个视频

      本文链接:https://www.haomeiwen.com/subject/uhnbdctx.html