Question

I am working on a video editing app in which I have to add audio file to a video and that is working fine if I add the audio at the start of video.

AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:audioURL options:nil];
    AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:videoURL options:nil];

    AVMutableComposition* mixComposition = [AVMutableComposition composition];

    AVMutableCompositionTrack *compositionCommentaryTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];


    [compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
    ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:kCMTimeZero error:nil];

    AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];


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

    AVAssetExportSession* _assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition
                                                                          presetName:AVAssetExportPresetPassthrough];

But what I want is that user can add the audio at any interval i.e. he will leave the first five seconds of video blank and will use audio for only the time frame after five seconds.

For that I tried to use this replacing kCMTimeZero with NewTime but the sound is not adding:

CCMTime Newtime=CMTimeMakeWithSeconds(3000.0, 600);

[compositionCommentaryTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration)
    ofTrack:[[audioAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] atTime:Newtime error:nil];

Is there anything wrong with the implementation or there is any other way to do that?please suggest.

Was it helpful?

Solution

I have got the solution:

I replaced CMTime Newtime=CMTimeMakeWithSeconds(3000.0, 600); with CMTime Newtime=CMTimeMake(3000, 600); this and its working fine.

OTHER TIPS

please be careful about CMTime and Time Scale in below code at means start time that we insert!!!

let at = CMTime(value: 3000, timescale: 1000)
        
try mutableCompositionAudioTrack[0].insertTimeRange(CMTimeRangeMake(start: .zero, duration: aVideoAssetTrack.timeRange.duration), of: aAudioAssetTrack, at: at)

value 3000 means 3 seconds and time scale means 3000/1000 = 3

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top