Sending audio stream usign asyncio

143 views Asked by At

I'm trying to stream microphone data to an asynchronous server. The client code is below. My first attempt was without using await asyncio.sleep(0), but the code was getting blocked. I imagine it was getting blocked because the process never finished, not allowing the event loop to consume the messages. Is this statement correct? When I added await asyncio.sleep(0), the event loop could be consumed.

Well, I imagine there's a more correct way to do this. What would it be? Would it be by spawning a thread in the client? Can someone provide me with a code snippet?

@sio.event
async def speechData(data):
    print("message received with ", data)


async def main():
    audio = pyaudio.PyAudio()
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 16000
    CHUNK = int(RATE / 10)

    await sio.connect("http://localhost:9000")
    await sio.emit(
        "startGoogleCloudStream",
        {
            "audio": {
                "encoding": "LINEAR16",
                "sampleRateHertz": 16000,
                "languageCode": "pt-BR",
            },
            "interimResults": True,
        },
    )

    stream = audio.open(
        format=FORMAT,
        channels=CHANNELS,
        rate=RATE,
        input=True,
        frames_per_buffer=CHUNK,
    )
    while True:
        data = stream.read(CHUNK)
        await sio.emit("binaryAudioData", data)
        await asyncio.sleep(0)

    # this shoud be here?
    await sio.wait()


if __name__ == "__main__":
    asyncio.run(main())
0

There are 0 answers