AudioFileWritePackets 失败(错误代码:1885563711 - 'kcp')

AudioFileWritePackets failed (error code: 1885563711 - 'kcp')

我目前正在尝试使用 AudioQueueInputCallback 将麦克风数据写入文件。我的代码回调如下所示:

func myAQInputCallback(inUserData: UnsafeMutableRawPointer?,
                       inQueue: AudioQueueRef,
                       inBuffer: AudioQueueBufferRef,
                       inStartTime: UnsafePointer<AudioTimeStamp>,
                       inNumPackets: UInt32,
                       inPacketDesc: UnsafePointer<AudioStreamPacketDescription>?) {
    var error: OSStatus
    var recorder = inUserData!.load(as: MyRecorder.self)

    // Is this neccessary?
    var tmpInOutNumPackets = inNumPackets

    if inNumPackets > 0 {
        error = AudioFileWritePackets(recorder.recordFile!,
                                      false,
                                      inBuffer.pointee.mAudioDataByteSize,
                                      inPacketDesc,
                                      recorder.recordPacket,
                                      &tmpInOutNumPackets,
                                      inBuffer.pointee.mAudioData)
        checkError(error, msg: "Couldn't write packet to audio file.")

        recorder.recordPacket += Int64(inNumPackets)
    }

    if recorder.running {
        error = AudioQueueEnqueueBuffer(inQueue, inBuffer, 0, nil)
        checkError(error, msg: "Couldn't enqueue buffer.")
    }
}

其中 MyRecorder 是一个 struct,看起来像这样:

struct MyRecorder {
    var recordFile: AudioFileID?
    var recordPacket: Int64
    var running: Bool
}

代码在 AudioFileWritePackets 调用时失败(错误代码:1885563711 - 'kcp')。什么会导致这里失败?

我很乐意提供更多信息,但目前我不知道哪些代码片段对这里有帮助。

另外,如您所见,我正在创建函数参数 inNumPackets 的临时副本,否则 AudioFileWritePackets 不会接受 &inNumPackets 作为参数(因为它是一个不可变 let-常量).

那个错误实际上是'pck?'kAudioFileInvalidPacketOffsetError,描述为

A packet offset was past the end of the file, or not at the end of the file when writing a VBR format, or a corrupt packet size was read when building the packet table.

问题可能与您没有使用实际写入的数据包数量有关,该数据在 AudioFileWritePackets returns 之后的 tmpInOutNumPackets 中找到。

所以试试

recorder.recordPacket += Int64(tmpInOutNumPackets)

相反。