Search code examples
objective-cavfoundationcore-audioavassetexportsession

Unable to trim an audio file with AVAssetExportSession


I'm trying to take a file from my iTunes library and produce a clipped/trimmed version of it. The problem I'm running into is that I tell it to trim on a specific time range. It trims with the right duration, but a different start time.

I'm using the export session method given in Trim audio with iOS.

This github project reproduces the issue. It's setup to trim starting at 10sec for a duration of 3 sec. What is produced is a clip with time range at around 0:12.1 to 0:15.1.

https://github.com/nickbolton/AVAssetExportSessionDebug.git

Any ideas as to why the trimmed time range is wrong? Thanks!


Solution

  • There's nothing wrong with your code per se.

    The problem you are experiencing is a direct artifact of the fact that you are starting with an MP3. It does not automatically provide accurate duration and timings. You have to ask for them.

    You are saying:

    AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:self.sourceAudioURL 
        options:nil]; 
    

    It's that nil options that's doing the damage. Instead, simply say:

    AVURLAsset* audioAsset = [[AVURLAsset alloc]initWithURL:self.sourceAudioURL 
        options:@{AVURLAssetPreferPreciseDurationAndTimingKey:@YES}];