Open random-yang opened 1 month ago
Hi, if you're working with AVAudioPCMBuffer
, you can convert these buffers directly into Data
and pass them into an AsyncThrowingStream
and can be used with the player:
final class PCMBufferTest {
private let player = AudioPlayer()
private var continuation: AsyncThrowingStream<Data, Error>.Continuation?
func startPlayback() {
player.start(AsyncThrowingStream { self.continuation = $0 })
}
func didReceivePCMBuffer(_ buffer: AVAudioPCMBuffer) {
guard let continuation, let data = Data(buffer: buffer) else { return }
continuation.yield(data)
}
func didFinishReceivingBuffers() {
continuation?.finish()
continuation = nil
}
}
extension Data {
init?(buffer: AVAudioPCMBuffer) {
let audioBuffer = buffer.audioBufferList.pointee.mBuffers
guard let bytes = audioBuffer.mData else { return nil }
self.init(bytes: bytes, count: Int(audioBuffer.mDataByteSize))
}
}
In my usage scenario, I need to be able to directly play a PCM data stream. Can this be done directly using this player? Or do I need to perform any conversions in advance. Sorry, I am still a beginner in the field of audio and video.