音视频拼接

文章目录
  1. 1. 将要拼接的音视频导入到项目中
  2. 2. 调用AVFoundation下的AVURLAsset等进行拼接
  3. 3. 注意点

前言:
在做音视频相关开发时会用到音视频拼接

将要拼接的音视频导入到项目中

调用AVFoundation下的AVURLAsset等进行拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

/**
* 拼接音频
*/
- (void)formateAudioFile{
/// 1.创建资源
AVURLAsset *audioAsset1 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"MBA材料撰写一.m4a" ofType:nil]]];
AVURLAsset *audioAsset2 = [AVURLAsset assetWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"MBA材料撰写二.m4a" ofType:@""]]];
/// 2.创建轨道
AVMutableComposition *composition = [AVMutableComposition composition];
/// 2.1 创建音频轨道
/// AVMediaTypeAudio : 音频 AVMediaTypeVideo :视频
AVMutableCompositionTrack *audioTrack1 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];
/// AVMediaTypeAudio : 音频 AVMediaTypeVideo :视频
AVMutableCompositionTrack *audioTrack2 = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:0];

/// 2.2 创建轨道素材
/// AVMediaTypeAudio : 音频 AVMediaTypeVideo :视频
AVAssetTrack *assetTrack1 = [audioAsset1 tracksWithMediaType:AVMediaTypeAudio].firstObject;
/// AVMediaTypeAudio : 音频 AVMediaTypeVideo :视频
AVAssetTrack *assetTrack2 = [audioAsset2 tracksWithMediaType:AVMediaTypeAudio].firstObject;
/// 2.3 将第一个轨道素材从零开始插入到轨道中
[audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration) ofTrack:assetTrack1 atTime:kCMTimeZero error:nil];
/// 2.4 将第二个轨道素材从第一个轨道结束时间开始插入到轨道中
[audioTrack2 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset2.duration) ofTrack:assetTrack2 atTime:audioAsset1.duration error:nil];
// 3.合并后的文件导出 - `presetName`要和之后的`session.outputFileType`相对应。
/// AVAssetExportPresetAppleM4A : 音频 AVAssetExportPresetLowQuality :视频
AVAssetExportSession *session = [[AVAssetExportSession alloc] initWithAsset:composition presetName:AVAssetExportPresetAppleM4A];
// 3.1 合并后的文件地址。
NSString *outPutFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"MBA材料撰写.m4a"];
if ([[NSFileManager defaultManager] fileExistsAtPath:outPutFilePath]) {
[[NSFileManager defaultManager] removeItemAtPath:outPutFilePath error:nil];
}
// 3.2 合并后的文件输入地址。
session.outputURL = [NSURL fileURLWithPath:outPutFilePath];
// AVFileTypeAppleM4A : 音频 AVFileTypeMPEG4 :视频
session.outputFileType = AVFileTypeAppleM4A; //与上述的`present`相对应
session.shouldOptimizeForNetworkUse = YES; //优化网络
// 3.3 开始合并
[session exportAsynchronouslyWithCompletionHandler:^{
if (session.status == AVAssetExportSessionStatusCompleted) {
NSLog(@"合并成功----%@", outPutFilePath);
} else {
// 其他情况, 具体请看这里`AVAssetExportSessionStatus`.
}
}];
}

注意点

1
2
3
/// 将第一个轨道素材从零开始插入到轨道中
/// 将第二个轨道素材从第一个轨道结束时间开始插入到轨
[audioTrack1 insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset1.duration) ofTrack:assetTrack1 atTime:kCMTimeZero error:nil];
分享到 评论