4

在过去的一周里,我一直在尝试从麦克风(在 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 的提示或设置?

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

4

0 回答 0