iOS – 更改每个AVAssetTrack的音量

我有一些audio文件需要在AVMutableComposition插入。 每个audio都有不同的音量。 为了做到这一点,我为每个audio文件创build了一个AVMutableTrackComposition和一个AVAssetTrack 。 所以我使用AVMutableAudioMix一个实例来改变每个音轨的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] 

使用单个AVMutableCompositionTrack与更多的AVAssetTrack关联,不允许我改变每个音轨的音量。

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

可以直接从AVAssetTrack更改音量?

  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有段,每个段有startTime和持续时间,您可以使用AVMutableAudioMixInputParameters更改每个CMTimeRange

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