Making a generator function an awaitable coroutine

Viewed 31

I'm trying to run a generator-based infinite loop in the background (Specifically, I want to run streaming speech recognition in the background). i.e., while I'm waiting for microphone input, I want to schedule other methods to run.

In the link above, audio data is generated using the following generator method:

# A part of MicrophoneStream class.
def generator(self):
    while not self.closed:
        chunk = self._buff.get()
        if chunk is None:
            return
        data = [chunk]

        while True:
            try:
                chunk = self._buff.get(block=False)
                if chunk is None:
                    return
                data.append(chunk)
            except queue.Empty:
                break

        yield b"".join(data)

And this generator() function is being used like this:

with MicrophoneStream(RATE, CHUNK) as stream:
    audio_generator = stream.generator()
    requests = (
        speech.StreamingRecognizeRequest(audio_content=content)
        for content in audio_generator
    )

    responses = client.streaming_recognize(streaming_config, requests)

    listen_print_loop(responses)

What I want is to functionally, is to call asyncio.sleep inside generator() so other tasks can get scheduled while waiting for I/O. But I'm not sure how to do this correctly (making generator() async and simply inserting asyncio.sleep in there doesn't seem to work).

Any ideas?

0 Answers
Related