mihai8804858 / swift-chunked-audio-player

Simple audio player for sync / async chunked audio streams
MIT License
30 stars 6 forks source link

Is it possible to support direct playback of PCM stream? #18

Open random-yang opened 1 month ago

random-yang commented 1 month ago

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.

mihai8804858 commented 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))
    }
}