更改编码器格式版本

时间:2019-06-24 04:12:40

标签: ios swift audio avaudioengine avaudiofile

过去一周,我一直在尝试从麦克风(在iOS上)中获取音频,对其进行下采样并将其写入“ .aac”文件。

我终于要指出它几乎可以正常工作了

let inputNode = audioEngine.inputNode
let inputFormat = inputNode.outputFormat(forBus: 0)

let bufferSize = UInt32(4096)
//let sampleRate = 44100.0
let sampleRate = 8000
let bitRate = sampleRate * 16

let fileUrl = url(appending: "NewRecording.aac")

print("Write to \(fileUrl)")
do {
    outputFile = try AVAudioFile(forWriting: fileUrl,
                                 settings: [
                                     AVFormatIDKey: kAudioFormatMPEG4AAC,
                                     AVSampleRateKey: sampleRate,
                                     AVEncoderBitRateKey: bitRate,
                                     AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
                                     AVNumberOfChannelsKey: 1],
                                 commonFormat: .pcmFormatFloat32,
                                 interleaved: false)
} catch let error {
    print("Failed to create audio file for \(fileUrl): \(error)")
    return
}

recordButton.setImage(RecordingStyleKit.imageOfMicrophone(fill: .red), for: [])

// Down sample the audio to 8kHz
let fmt = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: Double(sampleRate), channels: 1, interleaved: false)!
let converter = AVAudioConverter(from: inputFormat, to: fmt)!

inputNode.installTap(onBus: 0, bufferSize: AVAudioFrameCount(bufferSize), format: inputFormat) { (buffer, time) in

    let inputCallback: AVAudioConverterInputBlock = { inNumPackets, outStatus in
        outStatus.pointee = AVAudioConverterInputStatus.haveData
        return buffer
    }
    let convertedBuffer = AVAudioPCMBuffer(pcmFormat: fmt,
                                                                                 frameCapacity: AVAudioFrameCount(fmt.sampleRate) * buffer.frameLength / AVAudioFrameCount(buffer.format.sampleRate))!
    var error: NSError? = nil
    let status = converter.convert(to: convertedBuffer, error: &error, withInputFrom: inputCallback)
    assert(status != .error)

    if let outputFile = self.outputFile {
        do {
            try outputFile.write(from: convertedBuffer)
        }
        catch let error {
            print("Write failed: \(error)")
        }
    }
}

audioEngine.prepare()
do {
    try audioEngine.start()
}
catch {
    print(error.localizedDescription)
}

问题是,生成的文件必须为MPEG ADTS, AAC, v4 LC, 8 kHz, monaural格式,但是上面的代码仅生成MPEG ADTS, AAC, v2 LC, 8 kHz, monaural

也就是说,它必须是v4,而不是v2(我别无选择)

(此结果是通过在命令行上使用file {name}来转储其属性而生成的。我也使用MediaInfo提供了更多信息)

我一直在尝试找出是否有某种方法可以提供提示或设置AVAudioFile,从而将LC(低复杂度)版本从2更改为4?

我一直在浏览文档和示例,但似乎找不到任何建议

0 个答案:

没有答案