Подтвердить что ты не робот

В IOS AVFoundation Export Session отсутствует аудио

Я использую фреймворк iOS AVFoundation, и я могу успешно объединять видеодорожки с наложением изображений и текстовыми оверлеями. Однако мой выходной файл не сохраняет аудио в исходном исходном видео.

Как я могу убедиться, что источник звука из одного из моих видео остается с новым созданным мной видео?

ИЗМЕНИТЬ

* Используйте этот код, чтобы иметь хороший пример того, как выполнить это создание видео (с оригинальным аудио). Для меня не было очевидно, что мне нужно включать звуковую дорожку отдельно при обработке видео с помощью AVFoundation. Надеюсь, это поможет кому-то еще.

    AVAssetTrack *videoTrack = nil;
    AVAssetTrack *audioTrack = nil;
    CMTime insertionPoint = kCMTimeZero;

    if([[url tracksWithMediaType:AVMediaTypeVideo] count] != 0) {
        videoTrack = [url tracksWithMediaType:AVMediaTypeVideo][0];
    }

    if([[url tracksWithMediaType:AVMediaTypeAudio] count] != 0) {
        audioTrack = [url tracksWithMediaType:AVMediaTypeAudio][0];
    }

    // Insert the video and audio tracks from AVAsset
    if (videoTrack != nil) {
        AVMutableCompositionTrack *compositionVideoTrack = [videoComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
        [compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [url duration]) ofTrack:videoTrack atTime:insertionPoint error:&error];
    }
    if (audioTrack != nil) {
        AVMutableCompositionTrack *compositionAudioTrack = [videoComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
        [compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, [url duration]) ofTrack:audioTrack atTime:insertionPoint error:&error];
    }
4b9b3361

Ответ 1

Вот полный код, который решил это, у него есть два видео, которые сочетаются с их аудио: -

AVURLAsset* video1 = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:path1] options:nil];

AVURLAsset* video2 = [[AVURLAsset alloc]initWithURL:[NSURL fileURLWithPath:path2] options:nil];

if (video1 !=nil && video2!=nil) {

    // 1 - Create AVMutableComposition object. This object will hold your AVMutableCompositionTrack instances.
    AVMutableComposition *mixComposition = [[AVMutableComposition alloc] init];
    // 2 - Video track

    AVMutableCompositionTrack *firstTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];
    AVMutableCompositionTrack *firstTrackAudio = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio
                                                                        preferredTrackID:kCMPersistentTrackID_Invalid];

    [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, video1.duration)
                        ofTrack:[[video1 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:kCMTimeZero error:nil];
    [firstTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, video2.duration)
                        ofTrack:[[video2 tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] atTime:video1.duration error:nil];

//у него есть звуковая дорожка

    if ([[video1 tracksWithMediaType:AVMediaTypeAudio] count] > 0)
    {
        AVAssetTrack *clipAudioTrack = [[video1 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
        [firstTrackAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, video1.duration) ofTrack:clipAudioTrack atTime:kCMTimeZero error:nil];
    }

//у него есть звуковая дорожка

    if ([[video2 tracksWithMediaType:AVMediaTypeAudio] count] > 0)
    {
        AVAssetTrack *clipAudioTrack = [[video2 tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
        [firstTrackAudio insertTimeRange:CMTimeRangeMake(kCMTimeZero, video2.duration) ofTrack:clipAudioTrack atTime:video1.duration error:nil];
    }

//экспорт сеанса

    AVAssetExportSession *exporter = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                      presetName:AVAssetExportPresetHighestQuality];

    //Creates the path to export to  - Saving to temporary directory
    NSString* filename = [NSString stringWithFormat:@"Video_%d.mov",arc4random() % 1000];
    NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent:filename];

    //Checks if there is already a file at the output URL.  
    if ([[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        NSLog(@"Removing item at path: %@", path);
        [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
    }

    exporter.outputURL = [NSURL fileURLWithPath:path];
    //Set the output file type
    exporter.outputFileType = AVFileTypeQuickTimeMovie;


    path3=path;
    [arr_StoredDocumentoryUrls addObject:path3];

    //Exports!
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        switch (exporter.status) {
            case AVAssetExportSessionStatusCompleted:{
                NSLog(@"Export Complete");

                break;
            }
            case AVAssetExportSessionStatusFailed:
                NSLog(@"Export Error: %@", [exporter.error description]);
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export Cancelled");
                break;
            default:
                break;
        }
    }];

}

Ответ 2

Попробуйте добавить MobileCoreServices и выполнить.