我在 iOS 中使用 AVAudioEngine 从麦克风获取音频,并使用输入节点及其函数 installTap 将其写入缓冲区。
在 installTap 函数的 tapBlock 内部,它应该是读取和/或操作 PCM 缓冲区的地方,我需要调用一个 C 库函数,这个函数处理 PCM 缓冲区数据,它计算一个音频指纹,这个函数还需要读取一个文件,该文件是预先计算的音频指纹的数据库,以查找可能的匹配项。
问题是显然(如果我错了,请纠正我),你不能在这个块内进行任何文件 I/O 调用,因为这段代码正在另一个线程中运行,并且我传递给 C 端的文件指针始终为空或垃圾,这不会在此函数之外发生,(在主线程方面)指针有效,C 可以读取数据库文件。
如何在主线程中操作 PCM 缓冲区,以便进行文件 I/O 调用并能够计算 C 端所需的匹配?
我究竟做错了什么?
还有其他选择吗?谢谢。
import Foundation
import AVFoundation
let audioEngine = AVAudioEngine()
class AudioEngineTest: NSObject {
func setupAudioEngine() {
let input = audioEngine.inputNode
let inputFormat = input.outputFormat(forBus: 0)
let inputNode = audioEngine.inputNode;
//Convert received buffer to required format
let recordingFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: Double(44100), channels: 2, interleaved: false)
let formatConverter = AVAudioConverter(from:inputFormat, to: recordingFormat!)
let pcmBuffer = AVAudioPCMBuffer(pcmFormat: recordingFormat!, frameCapacity: AVAudioFrameCount(recordingFormat!.sampleRate * 4.0))
var error: NSError? = nil
inputNode.installTap(onBus: 0, bufferSize: AVAudioFrameCount(2048), format: inputFormat)
{
(buffer, time) in
let inputBlock: AVAudioConverterInputBlock = { inNumPackets, outStatus in
outStatus.pointee = AVAudioConverterInputStatus.haveData
return buffer
}
formatConverter?.convert(to: pcmBuffer!, error: &error, withInputFrom: inputBlock)
if error != nil {
print(error!.localizedDescription)
}
//Calling the function from the C library, passing it the buffer and the pointer to the db file: dbFilePathForC an UnsafeMutablePointer<Int8>
creatingFingerprintAndLookingForMatch(pcmbuffer, dbFilePathForC)
//In this scope, the pointer dbFilePathFoC is either null or garbage, so the C side of things cannot read the database file, outside of this scope, the same pointer works and C can read the file, but I cannot read the PCM buffer because it only exists inside this scope of this closure of installTap, called the tapBlock
}
try! audioEngine.start()
}
}
获取指向数据库文件的指针的代码块
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let dbPath = documentsPath+"/mydb.db"
do {
let text = try String(contentsOfFile: dbPath)
//converting dbPath to a pointer to be use in C
let cstringForDB = (dbPath as NSString).utf8String
let dbFilePathForC = UnsafeMutablePointer<Int8>(mutating: cstringForDB!);
} catch {
print("error cannot read the db file")
}