查看: 83|回复: 0

[教程] 在iOS中截取和分割音视频的代码示例

[复制链接]

2

主题

0

回帖

0

积分

积极分子

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2011-8-2
发表于 2025-5-20 08:26:47 | 显示全部楼层 |阅读模式

核心思路

截取或分割音视频的核心步骤如下:

  • 加载原始音视频文件AVURLAsset
  • 设置时间范围CMTimeRange)指定要截取的起始时间与持续时间
  • 创建导出会话AVAssetExportSession
  • 导出目标文件(支持 .mp4.m4a 等格式)
  • 处理异步导出完成回调

视频截取示例(Objective-C)

- (void)trimVideoFromURL:(NSURL *)inputURL startTime:(NSTimeInterval)startTime duration:(NSTimeInterval)duration completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    // 1. 创建导出会话
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
    
    // 2. 设置输出路径和文件格式
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"trimmedVideo.mp4"];
    exportSession.outputURL = [NSURL fileURLWithPath:outputPath];
    exportSession.outputFileType = AVFileTypeMPEG4;
    
    // 3. 设置时间范围(start ~ start + duration)
    CMTime startCMTime = CMTimeMakeWithSeconds(startTime, 600);
    CMTime durationCMTime = CMTimeMakeWithSeconds(duration, 600);
    CMTimeRange timeRange = CMTimeRangeMake(startCMTime, durationCMTime);
    exportSession.timeRange = timeRange;
    
    // 4. 异步导出
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (exportSession.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"视频截取成功: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = exportSession.error;
            NSLog(@"视频截取失败: %@", error.localizedDescription);
            if (completion) completion(nil, error);
        }
    }];
}

使用方法

NSURL *videoURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myVideo" ofType:@"mp4"]];
[self trimVideoFromURL:videoURL startTime:5.0 duration:10.0 completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"截取后的视频路径: %@", outputURL.path);
    }
}];

音频截取示例(Objective-C)

- (void)trimAudioFromURL:(NSURL *)inputURL startTime:(NSTimeInterval)startTime duration:(NSTimeInterval)duration completion:(void (^)(NSURL *outputURL, NSError *error))completion {
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetAppleM4A];
    
    NSString *outputPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"trimmedAudio.m4a"];
    exportSession.outputURL = [NSURL fileURLWithPath:outputPath];
    exportSession.outputFileType = AVFileTypeAppleM4A;
    
    CMTime startCMTime = CMTimeMakeWithSeconds(startTime, 600);
    CMTime durationCMTime = CMTimeMakeWithSeconds(duration, 600);
    CMTimeRange timeRange = CMTimeRangeMake(startCMTime, durationCMTime);
    exportSession.timeRange = timeRange;
    
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (exportSession.status == AVAssetExportSessionStatusCompleted) {
            NSLog(@"音频截取成功: %@", outputPath);
            if (completion) completion([NSURL fileURLWithPath:outputPath], nil);
        } else {
            NSError *error = exportSession.error;
            NSLog(@"音频截取失败: %@", error.localizedDescription);
            if (completion) completion(nil, error);
        }
    }];
}

使用方法

NSURL *audioURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"myAudio" ofType:@"mp3"]];
[self trimAudioFromURL:audioURL startTime:3.0 duration:5.0 completion:^(NSURL *outputURL, NSError *error) {
    if (outputURL) {
        NSLog(@"截取后的音频路径: %@", outputURL.path);
    }
}];

注意事项

项目说明
时间单位使用 CMTimeMakeWithSeconds 将秒数转换为 CMTime
输出路径使用 NSTemporaryDirectory() 可避免存储问题
输出格式视频推荐 .mp4,音频推荐 .m4a.caf
导出性能使用 AVAssetExportPresetLowQuality 可提升处理速度
错误处理检查 exportSession.statusexportSession.error

扩展建议

  • 多片段拼接:可结合 AVMutableComposition 实现多段裁剪后的内容拼接。
  • 后台导出:大文件建议在后台线程执行,避免阻塞主线程。
  • 第三方库:如需更复杂剪辑功能,可使用 FFmpeg-iOSGPUImage

总结

通过 AVAssetExportSessiontimeRange 属性,你可以轻松地从音视频文件中截取任意时间段的内容。这个方法既适用于音频也适用于视频,具有良好的兼容性和性能表现,是 iOS 音视频处理中的基础技能之一。

以上就是在iOS中截取和分割音视频的代码示例的详细内容,更多关于iOS截取和分割音视频的资料请关注琼殿技术社区其它相关文章!

您可能感兴趣的文章:
  • iOS中实现音视频合并的完整代码
  • iOS仿抖音视频加载动画效果的实现方法
  • iOS实现视频边播放边缓存的解决方案
  • iOS中tableView cell分割线的一些设置技巧
  • IOS 基础之设置 tableview 的分割线
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部