如何从流数据实现 AudioQueue

How to implement AudioQueue from streamed data

我正在尝试设置一个音频队列来播放流式音频数据。到目前为止,这就是我所拥有的:

    var audioStream = AudioStreamBasicDescription()
    audioStream.mSampleRate = 44100
    audioStream.mFormatID = kAudioFormatAppleLossless
    audioStream.mFramesPerPacket = 352
    audioStream.mChannelsPerFrame = 2

    AudioQueueNewOutputWithDispatchQueue(
        &self.playerState.queue, // nil `AudioQueueRef?`
        &audioStream,
        0,
        self.callback) { aq, buffer in
            self.output(self.playerState, aq: aq, buffer: buffer)
    }

这是我不太确定的地方

func output (_ playerState: PlayerState, aq: AudioQueueRef, buffer: AudioQueueBufferRef)

基本上,playerState 有几个音频数据包我(认为我)需要复制到缓冲区 (AudioQueueBufferRef)。除此之外,我不太确定。

不确定它是否有帮助,但是,这是一个示例音频包:

[32, 0, 0, 4, 6, 19, 8, 8, 129, 249, 214, 3, 147, 251, 90, 19, 8, 9, 187, 248, 253, 255, 186, 0, 57, 255, 6, 130, 134, 131, 3, 6, 4, 129, 0, 192, 129, 193, 194, 6, 8, 12, 16, 81, 100, 201, 157, 185, 135, 163, 49, 109, 117, 97, 89, 101, 93, 49, 41, 33, 37, 29, 13, 17, 12, 237, 138, 180, 101, 70, 131, 12, 3, 6, 1, 196, 24, 129, 16, 197, 24, 67, 58, 210, 113, 153, 209, 207, 93, 244, 219, 28, 98, 18, 74, 48, 200, 76, 204, 70, 80, 33, 175, 16, 210, 124, 243, 215, 90, 80, 141, 145, 32, 33, 138, 75, 20, 149, 141, 80, 200, 204, 142, 115, 110, 125, 248, 226, 245, 2, 212, 181, 40, 226, 47, 150, 156, 105, 148, 49, 145, 153, 26, 51, 76, 153, 8, 140, 37, 46, 249, 203, 143, 55, 236, 228, 130, 239, 149, 172, 217, 140, 205, 70, 204, 35, 177, 230, 252, 242, 210, 85, 35, 13, 214, 54, 165, 243, 157, 229, 125, 4, 205, 20, 17, 223, 34, 173, 52, 67, 52, 118, 106, 119, 170, 206, 112, 65, 85, 200, 214, 187, 136, 69, 74, 57, 133, 107, 139, 73, 96, 243, 49, 56, 181, 34, 55, 231, 213, 179, 165, 140, 208, 131, 172, 215, 247, 41, 176]

我的问题是如何

A) 将数据复制到缓冲区并

B) 从音频队列/缓冲区播放音频?

编辑:这是在 MacOS 上而不是 iOS

A) 将数据复制到缓冲区

let maxIndex = playerState.packets.count - 1
let index = Int(packet.sequenceNumber) & maxIndex
guard writePacket(packet, to: index) else { return }

然后,您必须更新写入索引和播放状态。

B) 要开始播放设置播放器的状态,您必须加载缓冲区,将它们排入队列,然后设置 playerState :

self.playerState.isPlaying = true

并开始播放音频:

AudioQueueStart(playerState.queue, nil)

对于带有错误处理的完全成熟的实现,请查看 here