我需要将使用 2 个音频通道录制的 .wav 文件转换为只有 1 个通道的 .wav 文件,并将位深度从 32 减少到 16。我一直在尝试使用AVAudioConverter.convertToBuffer
但是,转换会引发错误:Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"
基本上,唯一真正需要改变的是将音频剥离到单个通道和位深度。我从不同的工具获取这些文件,所以我不能只改变文件的记录方式。
我在处理音频方面并不是那么出色,而且我有点难过。我正在处理的代码如下 - 我有什么遗漏吗?
let inAudioFileURL:NSURL = <url_to_wav_file>
var inAudioFile:AVAudioFile?
do
{
inAudioFile = try AVAudioFile(forReading: inAudioFileURL)
}
catch let error
{
print ("error: \(error)")
}
let inAudioFormat:AVAudioFormat = inAudioFile!.processingFormat
let inFrameCount:UInt32 = UInt32(inAudioFile!.length)
let inAudioBuffer:AVAudioPCMBuffer = AVAudioPCMBuffer(PCMFormat: inAudioFormat, frameCapacity: inFrameCount)
do
{
try inAudioFile!.readIntoBuffer(inAudioBuffer)
}
catch let error
{
print ("readError: \(error)")
}
let startFormat:AVAudioFormat = AVAudioFormat.init(settings: inAudioFile!.processingFormat.settings)
print ("startFormat: \(startFormat.settings)")
var endFormatSettings = startFormat.settings
endFormatSettings[AVLinearPCMBitDepthKey] = 16
endFormatSettings[AVNumberOfChannelsKey] = 1
endFormatSettings[AVEncoderAudioQualityKey] = AVAudioQuality.Medium.rawValue
print ("endFormatSettings: \(endFormatSettings)")
let endFormat:AVAudioFormat = AVAudioFormat.init(settings: endFormatSettings)
let outBuffer = AVAudioPCMBuffer(PCMFormat: endFormat, frameCapacity: inFrameCount)
let avConverter:AVAudioConverter = AVAudioConverter.init(fromFormat: startFormat, toFormat: endFormat)
do
{
try avConverter.convertToBuffer(outBuffer, fromBuffer: inAudioBuffer)
}
catch let error
{
print ("avconverterError: \(error)")
}
至于输出:
startFormat:
["AVSampleRateKey": 16000,
"AVLinearPCMBitDepthKey": 32,
"AVLinearPCMIsFloatKey": 1,
"AVNumberOfChannelsKey": 2,
"AVFormatIDKey": 1819304813,
"AVLinearPCMIsNonInterleaved": 0,
"AVLinearPCMIsBigEndianKey": 0]
endFormatSettings:
["AVSampleRateKey": 16000,
"AVLinearPCMBitDepthKey": 16,
"AVLinearPCMIsFloatKey": 1,
"AVNumberOfChannelsKey": 1,
"AVFormatIDKey": 1819304813,
"AVLinearPCMIsNonInterleaved": 0,
"AVLinearPCMIsBigEndianKey": 0,
"AVEncoderQualityKey": 64]
avconverterError: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"