iOS 视频拼接以及添加背景音乐

- (void)joinVideoAndMusic {
    NSURL *videoURL1 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_4400" ofType:@"m4v"]];
    NSURL *videoURL2 = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"IMG_5170" ofType:@"mp4"]];
    NSURL *musicURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"littlelucky" ofType:@"mp3"]];
    AVAsset *asset1 = [AVAsset assetWithURL:videoURL1];
    AVAsset *asset2 = [AVAsset assetWithURL:videoURL2];
    AVAsset *asset3 = [AVAsset assetWithURL:musicURL];
    
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    AVMutableCompositionTrack *videoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
    [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset1.duration) ofTrack:[asset1 tracksWithMediaType:AVMediaTypeVideo].firstObject atTime:kCMTimeZero error:nil];
    [videoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, asset2.duration) ofTrack:[asset2 tracksWithMediaType:AVMediaTypeVideo].firstObject atTime:asset1.duration error:nil];
    if (asset3 != nil) {
        AVMutableCompositionTrack *audioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [audioTrack insertTimeRange:CMTimeRangeMake(CMTimeAdd(asset1.duration, asset2.duration), CMTimeAdd(asset1.duration, asset2.duration)) ofTrack:[asset3 tracksWithMediaType:AVMediaTypeAudio].firstObject atTime:kCMTimeZero error:nil];
        
        _audioMix = [AVMutableAudioMix audioMix];
        if (asset3) {
            AVMutableAudioMixInputParameters *audioParam = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:audioTrack];
            [audioParam setVolumeRampFromStartVolume:0 toEndVolume:1 timeRange:CMTimeRangeMake(kCMTimeZero,asset1.duration)];
            [audioParam setVolumeRampFromStartVolume:1 toEndVolume:0 timeRange:CMTimeRangeMake(asset1.duration, asset2.duration)];
            [audioParam setTrackID:audioTrack.trackID];
            _audioMix.inputParameters = @[audioParam];
        }
    }
    
    NSString *outputPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/CustomMovie.mp4"];
    unlink([outputPath UTF8String]);   // 删除当前该路径下的文件
    NSURL *outputURL = [NSURL fileURLWithPath:outputPath];
    
    
    _exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetHighestQuality];
    _exporter.outputURL = outputURL;
    _exporter.outputFileType = AVFileTypeQuickTimeMovie;
    _exporter.shouldOptimizeForNetworkUse = YES;
    _exporter.audioMix = _audioMix;
    __weak typeof(self) weakSelf = self;
    [_exporter exportAsynchronouslyWithCompletionHandler:^{
        // 视频输出完成
        switch (weakSelf.exporter.status) {
            case AVAssetExportSessionStatusCompleted:
                [weakSelf saveVideoToLibrary:outputPath];
                break;
            case AVAssetExportSessionStatusFailed:
                kShowPopTip(nil, @"导出失败", nil);
                break;
            case AVAssetExportSessionStatusCancelled:
                kShowPopTip(nil, @"导出取消", nil);
                break;
            default:
                break;
        }
    }];
}
- (void)saveVideoToLibrary:(NSString *)outputPath {
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        
        __block PHObjectPlaceholder *placeholder;
        if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(outputPath)) {
            NSError *error;
            [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
                PHAssetChangeRequest* createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL URLWithString:outputPath]];
                placeholder = [createAssetRequest placeholderForCreatedAsset];
            } error:&error];
            if (error) {
                kShowPopTip(self.view, error.description, nil);
            }else {
                kShowPopTip(self.view, @"视频已保存到相册", nil);
            }
        }
    }
}

你可能感兴趣的:(iOS 视频拼接以及添加背景音乐)