iOS - 更改每个AVAssetTrack的音量

时间:2015-05-12 02:11:56

标签: ios swift avmutablecomposition

我需要在AVMutableComposition中插入一些音频文件。每个音频都有不同的音量。为此,我为每个音频文件创建了AVMutableTrackCompositionAVAssetTrack。所以我使用AVMutableAudioMix的实例更改了每个曲目的音量。

let composition = AVMutableComposition()
var trackMixArray = NSMutableArray()

for audio in layer{
   let trackAudio:AVMutableCompositionTrack = composition.addMutableTrackWithMediaType(AVMediaTypeAudio, preferredTrackID: CMPersistentTrackID())

   let file = project.stringByAppendingPathComponent(audio.name)
   let soundAsset = AVURLAsset(URL: NSURL(fileURLWithPath: file), options: option as [NSObject : AnyObject])
   let sounds = soundAsset.tracksWithMediaType(AVMediaTypeAudio)
   var sound:AVAssetTrack = sounds[0] as! AVAssetTrack
   let duration:CMTime = sound.timeRange.duration

   let audioTimeRange:CMTimeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, duration)
   let start:CMTime = CMTimeMakeWithSeconds(audio.start.toDouble()!, 600)
   let stop:CMTime = CMTimeMakeWithSeconds(audio.stop.toDouble()!, 600)

   let trackMix = AVMutableAudioMixInputParameters(track: trackAudio)
   trackMix.setVolume(audio.volume, atTime: kCMTimeZero)
   trackMixArray.addObject(trackMix)

   trackAudio.insertTimeRange(audioTimeRange, ofTrack: sound, atTime: start, error: nil)
 }

let audioMix = AVMutableAudioMix()
audioMix.inputParameters = trackMixArray as [AnyObject]

使用单个AVMutableCompositionTrackAVAssetTrack关联的 let trackMix = AVMutableAudioMixInputParameters(track: sound) trackMix.setVolume(audio.volume, atTime: kCMTimeZero) trackMixArray.addObject(trackMix) 不允许我更改每个曲目的音量。

AVAssetTrack

可以直接从int size = array.size();

更改音量

1 个答案:

答案 0 :(得分:0)

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

    ... 
    AVAssetExportSession Magic
    ...
    generalExporter = [[AVAssetExportSession alloc] initWith...
    generalExporter.audioMix = audioMix;

这可以帮助您更改每个音轨的音量,只需将其更改为快速。

编辑: 每个AVMutableCompositionTrack都有细分,每个细分都有开始时间和持续时间,您可以使用AVMutableAudioMixInputParameters来更改每个CMTimeRange

的数量
 - (void)setVolumeRampFromStartVolume:(float)startVolume
                         toEndVolume:(float)endVolume
                           timeRange:(CMTimeRange)timeRange