#How do you run a realtime tasks on multiprocessing Queue.get() without blocking?

1 messages · Page 1 of 1 (latest)

fresh lagoon
#

I have a script that generates a Queue of audio that I want to play in which I start in a separate thread.

from multiprocessing import Process, Queue
audio_queue = Queue()

if __name__ == '__main__':
    agent_process = Process(target=agent.main, args=(audio_queue,))
    agent_process.start()

    bot.run(bot_token)

Now that I have a Queue, I couldn't find a way to now stream whenever something comes in from that Queue into the VoiceClient.

My non discord bot test script would just start another thread with a while loop and wait for Queue.get() to stream audio with pyaudio. But I cant do something similar with that in pycord.

I could not figure out any efficient way to do this either with tasks. It would be a pain to significantly alter the Queue system for audio because other parts rely on it.

audio_thread = Thread(target=audio_player, args=(audio_queue,))
audio_thread.start()

...

def audio_player(audio_queue):
    # Initialize PyAudio
    p = pyaudio.PyAudio()

    while True:
        audio = audio_queue.get()
        if audio is None:
            break
        print("Playing audio...")
        try:
            # Open the audio stream
            playback_stream = p.open(format=pyaudio.paInt32,  # Assuming 16-bit PCM
                                     channels=audio.channels,  # Mono audio
                                     rate=audio.frame_rate,  # Sample rate
                                     output=True)

            playback_stream.write(audio.raw_data)

            playback_stream.stop_stream()
            playback_stream.close()

            time.sleep(0.4)
        except Exception as e:
            print(f"Error playing audio: {e}")
    p.terminate()
solemn notch
#

.rie

manic bayBOT
#

You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...

@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.

solemn notch
#

I think this or async version of ur thing of it exist

fresh lagoon
#

I settled on a less blocking method by using if Queue.empty() and doing an await with asyncio.sleep(0.1). I’ll check this out when I eventually have to add the recording part.

analog needle