Merge video files with their original audio in iOS

风流意气都作罢 提交于 2019-12-12 08:56:30

问题


I need to merge two video files along with their corresponding audio. I tried using : http://www.raywenderlich.com/13418/how-to-play-record-edit-videos-in-ios

The videos gets merged, but their audio is missing. It's like a muted video. I need the audio also to be merged. I also googled on this, couldn't find anything useful. Can someone help me on this please...


回答1:


Live-editing audio is exactly like live-editing video. Go back to each movie and fetch the audio track and stick it into your mutable composition.

In this example, I grab the first five seconds of video and the last five seconds of video from a movie and put them one after the other in a new video:

NSString* type = AVMediaTypeVideo;
NSArray* arr = [oldAsset tracksWithMediaType:type];
AVAssetTrack* track = [arr lastObject];
CMTime duration = track.timeRange.duration;
AVMutableComposition* comp = [AVMutableComposition composition];
AVMutableCompositionTrack* comptrack = [comp addMutableTrackWithMediaType:type preferredTrackID:kCMPersistentTrackID_Invalid];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(0,600), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(0,600) error:nil];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeSubtract(duration, CMTimeMakeWithSeconds(5,600)), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(5,600) error:nil];

But the resulting video would be silent. So I also go back and fetch the corresponding audio:

type = AVMediaTypeAudio;
arr = [oldAsset tracksWithMediaType:type];
track = [arr lastObject];
comptrack = [comp addMutableTrackWithMediaType:type preferredTrackID:kCMPersistentTrackID_Invalid];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeMakeWithSeconds(0,600), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(0,600) error:nil];
[comptrack insertTimeRange:CMTimeRangeMake(CMTimeSubtract(duration, CMTimeMakeWithSeconds(5,600)), CMTimeMakeWithSeconds(5,600)) ofTrack:track atTime:CMTimeMakeWithSeconds(5,600) error:nil];


来源:https://stackoverflow.com/questions/22715881/merge-video-files-with-their-original-audio-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!