是否有可能增加/减少音频文件的AVAsset轨道或AVMutableComposition的音量?我有两个音频文件(背景乐器和录音歌曲),我想减少一个文件的音量,并与其他文件合并。
发布于 2018-07-06 12:30:09
1.改变轨道的音量
要对物理文件执行此操作,需要将原始PCM数据加载到Swift中。下面是通过这篇文章是:获取浮点数据的示例
import AVFoundation
// ...
let url = NSBundle.mainBundle().URLForResource("your audio file", withExtension: "wav")
let file = try! AVAudioFile(forReading: url!)
let format = AVAudioFormat(commonFormat: .PCMFormatFloat32, sampleRate: file.fileFormat.sampleRate, channels: 1, interleaved: false)
let buf = AVAudioPCMBuffer(PCMFormat: format, frameCapacity: 1024)
try! file.readIntoBuffer(buf)
// this makes a copy, you might not want that
let floatArray = Array(UnsafeBufferPointer(start: buf.floatChannelData[0], count:Int(buf.frameLength)))
print("floatArray \(floatArray)\n")一旦floatArray中有了数据,只需将数组中的每个值乘以0到1之间的数字即可调整增益。如果您对分贝比较熟悉,那么将分贝值放入下面的一行,并将每个数组值乘以linGain
var linGain = pow(10.0f, decibelGain/20.0f)。
然后是在加载音频文件(信用)之前再次写入音频文件的问题:
let SAMPLE_RATE = Float64(16000.0)
let outputFormatSettings = [
AVFormatIDKey:kAudioFormatLinearPCM,
AVLinearPCMBitDepthKey:32,
AVLinearPCMIsFloatKey: true,
// AVLinearPCMIsBigEndianKey: false,
AVSampleRateKey: SAMPLE_RATE,
AVNumberOfChannelsKey: 1
] as [String : Any]
let audioFile = try? AVAudioFile(forWriting: url, settings: outputFormatSettings, commonFormat: AVAudioCommonFormat.pcmFormatFloat32, interleaved: true)
let bufferFormat = AVAudioFormat(settings: outputFormatSettings)
let outputBuffer = AVAudioPCMBuffer(pcmFormat: bufferFormat, frameCapacity: AVAudioFrameCount(buff.count))
// i had my samples in doubles, so convert then write
for i in 0..<buff.count {
outputBuffer.floatChannelData!.pointee[i] = Float( buff[i] )
}
outputBuffer.frameLength = AVAudioFrameCount( buff.count )
do{
try audioFile?.write(from: outputBuffer)
} catch let error as NSError {
print("error:", error.localizedDescription)
}2.把铁轨混在一起
一旦您有了新的音频.wav文件,您就可以像以前一样将这两个文件加载到AVAssets中,但这一次您可以像以前一样使用所需的增益。
然后看起来你会想要使用AVAssetReaderAudioMixOutput,它有一个专门用于混合两个音频轨道的方法。
AVAssetReaderAudioMixOutput.init(audioTracks: [AVAssetTrack], audioSettings: [String : Any]?)备注:I不会连续使用步骤1和步骤2--例如,如果您想将歌曲与滑块混合起来并听到结果,我建议使用AVPlayer并调整其音量,然后当用户准备就绪时,调用此文件IO并进行混合。
https://stackoverflow.com/questions/51153929
复制相似问题