在iOS中截取和分割音視頻的代碼示例
更新時間:2025年05月20日 08:26:47 作者:90后晨仔
在 iOS 開發(fā)中,截取或分割音視頻是常見需求,適用于短視頻剪輯、語音消息裁剪、媒體內容編輯等場景,使用 AVFoundation 框架可以高效實現(xiàn)這一功能,下面將詳細介紹如何在 iOS 中截取或分割音視頻,并提供完整的代碼示例和使用方法,需要的朋友可以參考下
核心思路
截取或分割音視頻的核心步驟如下:
- 加載原始音視頻文件(
AVURLAsset) - 設置時間范圍(
CMTimeRange)指定要截取的起始時間與持續(xù)時間 - 創(chuàng)建導出會話(
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. 創(chuàng)建導出會話
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 將秒數(shù)轉換為 CMTime |
| 輸出路徑 | 使用 NSTemporaryDirectory() 可避免存儲問題 |
| 輸出格式 | 視頻推薦 .mp4,音頻推薦 .m4a 或 .caf |
| 導出性能 | 使用 AVAssetExportPresetLowQuality 可提升處理速度 |
| 錯誤處理 | 檢查 exportSession.status 和 exportSession.error |
擴展建議
- 多片段拼接:可結合
AVMutableComposition實現(xiàn)多段裁剪后的內容拼接。 - 后臺導出:大文件建議在后臺線程執(zhí)行,避免阻塞主線程。
- 第三方庫:如需更復雜剪輯功能,可使用 FFmpeg-iOS 或 GPUImage。
總結
通過 AVAssetExportSession 的 timeRange 屬性,你可以輕松地從音視頻文件中截取任意時間段的內容。這個方法既適用于音頻也適用于視頻,具有良好的兼容性和性能表現(xiàn),是 iOS 音視頻處理中的基礎技能之一。
以上就是在iOS中截取和分割音視頻的代碼示例的詳細內容,更多關于iOS截取和分割音視頻的資料請關注腳本之家其它相關文章!
相關文章
IOS ObjectC與javascript交互詳解及實現(xiàn)代碼
這篇文章主要介紹了IOS OC與js交互詳解及實現(xiàn)代碼的相關資料,需要的朋友可以參考下2017-03-03
iOS使用UICollectionView實現(xiàn)橫向滾動照片效果
這篇文章主要為大家詳細介紹了iOS使用UICollectionView實現(xiàn)橫向滾動照片效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-05-05
iOS開發(fā)中使用Quartz2D繪制上下文棧和矩陣的方法
這篇文章主要介紹了iOS開發(fā)中使用Quartz2D繪制上下文棧和矩陣的方法,代碼基于傳統(tǒng)的Objective-C,需要的朋友可以參考下2015-11-11

