iOS 9 : AVFoundation Export Session is missing aud

2019-06-03 15:16发布

问题:

I'm using the below code snipped while merging videos with original audio. It has been working until I upgraded to iOS9. Anyone faced the same issue and any help to resolve would be greatly appreciated. I couldn't find anything after researching whole day.

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];
}

回答1:

Found the issue: I have used the below after the above code. After removing this it worked fine. The below extra line removes the already added audio track in iOS 9. Hope it helps someone!

AVMutableCompositionTrack *compositionAudioTrack2 = [videoComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];



回答2:

I have had a similar problem, but my observation is that you can not add an audio track with no audio anymore. IOS 9 will then remove the complete audio.

So only this line will remove all audio 
compositionAudioTrack = [videoComposition 
addMutableTrackWithMediaType:AVMediaTypeAudio 
preferredTrackID:kCMPersistentTrackID_Invalid];

if not followed with a valid

[compositionAudioTrack insertTimeRange:
     CMTimeRangeMake(kCMTimeZero, [url duration]) 
     ofTrack:audioTrack 
     atTime:insertionPoint error:&error];

So the test on audioTrack != nil is not enough.

I combine two audio tracks with one video with no problems anymore for IOS 9.