用AVAssetExportSession導出一個修剪的音頻


用AVAssetExportSession導出一個修剪的音頻

當創建一個 .m4a 輸出文件時,該如何配置一個AVAssetExportSession對象修剪音頻並執行淡出 ?

AVAssetExportSession對象用於轉換AVAsset源的內容,有很多可配置的屬性,允許自定義導出操作。由指定的預置的來描述輸出,例如AVAssetExportPresetAppleM4A將只生成.m4a文件。

// 演示了一個AVAssetExportSession對象的基本配置,該對象需要導出一個音頻資源,該資源被縮減到20秒,並有10秒的淡入時間。在代碼段中設置的修剪發生在資源的30秒標記處,因此跟蹤持續時間應該至少為50秒。
- (BOOL)exportAsset:(AVAsset *)avAsset toFilePath:(NSString *)filePath {
    
    // 前提需要一個至少50s的音頻資源
    CMTime assetTime = [avAsset duration];
    Float64 duration = CMTimeGetSeconds(assetTime);
    if (duration < 50.0) return NO;
    
    // 獲取第一個音軌
    NSArray *tracks = [avAsset tracksWithMediaType:AVMediaTypeAudio];
    if ([tracks count] == 0) return NO;
    
    AVAssetTrack *track = [tracks objectAtIndex:0];
    
    // 創建導出會話
    AVAssetExportSession *exportSession = [AVAssetExportSession exportSessionWithAsset:avAsset presetName:AVAssetExportPresetAppleM4A];
    
    if (exportSession == nil) return NO;
    
    // 創建一個裁剪范圍 從30s開始的一個20s時長
    CMTime startTime = CMTimeMake(30, 1);
    CMTime stopTime = CMTimeMake(50, 1);
    CMTimeRange exportTimeRange = CMTimeRangeFromTimeToTime(startTime, stopTime);
    
    // 創建一個淡出時間范圍,從修剪的時間開始的10s
    CMTime startFadeInTime = startTime;
    CMTime endFadeInTime = CMTimeMake(40, 1);
    CMTimeRange fadeInTimeRange = CMTimeRangeFromTimeToTime(startFadeInTime, endFadeInTime);
    
    // 創建音頻混響
    AVMutableAudioMix *exportAudioMix = [AVMutableAudioMix audioMix];
    AVMutableAudioMixInputParameters *exportAudioMixInputParameters = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:track];
    [exportAudioMixInputParameters setVolumeRampFromStartVolume:0.0 toEndVolume:1.0 timeRange:fadeInTimeRange];
    exportAudioMix.inputParameters = @[exportAudioMixInputParameters];
    
    // 配置導出會話
    exportSession.outputURL = [NSURL fileURLWithPath:filePath]; // output path
    exportSession.outputFileType = AVFileTypeAppleM4A; // output file type
    exportSession.timeRange = exportTimeRange; // trim time range
    exportSession.audioMix = exportAudioMix; // fade in audio mix
    
    // 執行導出
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        if (AVAssetExportSessionStatusCompleted == exportSession.status) {
            NSLog(@"completed");
        } else if (AVAssetExportSessionStatusFailed == exportSession.status) {
            NSLog(@"failed");
        } else {
            NSLog(@"Export Seesion Status: %zd", exportSession.status);
        }
    }];
    
    
    return YES;
}

Apple 參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM