如何在AVMutableComposition中改变音轨的音量

问题描述 投票:1回答:1

我一直在尝试使用不同的方法来解决此问题,但是它们花费的时间太长(更改MP3文件以用于不同的卷)。

我有一个AVMutableComposition,其中填充了多个用于音频和视频的AVMutableCompositionTrack。混合效果很好,但是音轨的音量调整无法正常工作,并且在导出时失败。

这是我使用的代码:

AVMutableComposition* mixComposition = [AVMutableComposition composition];
AVURLAsset *soundTrackAsset = [[AVURLAsset alloc]initWithURL:trackTempProcessedURL options:nil];

//ADDING AUDIO
AVMutableCompositionTrack *compositionAudioSoundTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:trackIDSoundTrack];
[compositionAudioSoundTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, audioAsset.duration) 
                                    ofTrack:[[soundTrackAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0] 
                                     atTime:CMTimeAdd(cmTimeDifference,startTime) error:nil];

NSArray *tracksToDuck = [mixComposition tracksWithMediaType:AVMediaTypeAudio];
NSMutableArray *trackMixArray = [NSMutableArray array];
for (NSInteger i = 0; i < [tracksToDuck count]; i++) {
    AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:[tracksToDuck objectAtIndex:i]];
    [trackMix setVolume:volume atTime:kCMTimeZero];   
    [trackMixArray addObject:trackMix];
 }
 audioMix = [AVMutableAudioMix audioMix];
 audioMix.inputParameters = trackMixArray;

//ADDING VIDEO
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:frontAssetURL options:nil];
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) 
                               ofTrack:[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0]
                                atTime:startTime error:nil];

//EXPORTING
_assetExport = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName: AVAssetExportPresetPassthrough];

_assetExport.outputFileType = AVFileTypeQuickTimeMovie; 
_assetExport.outputURL = exportUrl;
_assetExport.shouldOptimizeForNetworkUse = YES;
_assetExport.audioMix = audioMix;  

[_assetExport exportAsynchronouslyWithCompletionHandler:
 ^(void ) { 
 ...

没有音频混音器,一切混合都很好,但是当我尝试改变音量时,导出会给我一个错误:

AVFoundationErrorDomain Error: 11822
ios avfoundation avassetexportsession
1个回答
1
投票

[AVMutableAudioMixInputParameters需要设置“ trackID”来指示应该应用该参数的音轨。

for (NSInteger i = 0; i < [tracksToDuck count]; i++) {
    AVMutableAudioMixInputParameters *trackMix = [AVMutableAudioMixInputParameters audioMixInputParametersWithTrack:[tracksToDuck objectAtIndex:i]];
    [trackMix setVolume:volume atTime:kCMTimeZero];   

//+++++code
    AVMutableCompositionTrack * track = [tracksToDuck objectAtIndex:i]
    [trackMix setTrackID:[track trackID]];

    [trackMixArray addObject:trackMix];
}
© www.soinside.com 2019 - 2024. All rights reserved.