You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AVFoundation缩放音频时间范围后播放及导出出现杂音的问题求助

AVFoundation缩放音频时间范围后播放及导出出现杂音的问题求助

大家好,我正在用AVFoundation开发一个多轨音频编辑器,支持添加多轨道、分割/插入音频片段,还需要实现片段变速的功能(不过我也在纠结AVFoundation是不是做这个的最优选择)。目前遇到一个棘手的问题:当我用scaleTimeRange API对音频片段做变速处理后,播放合成内容时会出现短暂的“啪”声杂音;更麻烦的是,有时候用AVPlayer播放合成结果时杂音可能不明显,但用AVAssetReader导出成品文件后,杂音会很清晰地存在。

我做了一个简化的测试示例,核心代码如下,大家可以直接复现问题:

AVAudioSession.sharedInstance().setCategory(.playback)

let composition = AVMutableComposition()
let asset = AVURLAsset(url: Bundle.main.url(forResource: "1", withExtension: "mp3")!)
let originalTrack = asset.tracks(withMediaType: .audio).first!

let divideTime: CMTime = CMTime(seconds: 2, preferredTimescale: 44100)
let timeRange1 = CMTimeRange(start: CMTime(value: .zero, timescale: 44100), end: divideTime)
let timeRange2 = CMTimeRange(start: divideTime, end: asset.duration)

let track = composition.addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid)!
try! track.insertTimeRange(timeRange1, of: originalTrack, at: .zero)
try! track.insertTimeRange(timeRange2, of: originalTrack, at: timeRange1.end)

// 对第二段音频做2倍速缩放,这行代码会导致播放时出现“啪”声杂音
// 注释掉这行再播放,杂音就会消失
track.scaleTimeRange(timeRange2, toDuration: CMTimeMultiplyByFloat64(timeRange2.duration, multiplier: 0.5))

let playerItem = AVPlayerItem(asset: composition)
let mix = AVMutableAudioMix()
let params = AVMutableAudioMixInputParameters(track: track)
params.setVolume(1, at: .zero)
mix.inputParameters.append(params)
playerItem.audioMix = mix

player.replaceCurrentItem(with: playerItem)
self.player.play()

具体的问题场景是:我把一段音频分割成前后两段,插入到同一个合成轨道中,然后对第二段做2倍速压缩(把时长缩短为原来的一半)。只要执行了缩放操作,在两段音频的衔接处就会出现明显的杂音;如果注释掉缩放的代码,播放合成后的音频就完全正常,没有杂音。

我想请教大家:

  • 这种杂音是怎么产生的?是不是AVFoundation在做音频变速时,没有处理好音频片段的衔接过渡?
  • 有没有什么方法可以避免这种杂音?比如在缩放前后添加淡入淡出,或者调整AVFoundation的某些配置?
  • 另外,导出时的杂音问题是不是和播放时的问题同源?有没有针对导出流程的特殊处理技巧?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:44:30