How do I create an audio queue?

I’m using streamlit as as a voice assistent where the messages between the user and the LLM is played back using st.markdown since there is currently no autoplay option for st.audio. The problem I have is that if a message is already being played I want to wait until that is finished before playing the next message. Any ideas how to solve this as I have been trying to get it to work without any success.

This is the function I call everytime there is a new meessage.

def autoplay_audio(audio_file_name: str):
    file_path = f'audio/{audio_file_name}.mp3'
    with open(file_path, "rb") as f:
        data = f.read()
        b64 = base64.b64encode(data).decode()
        md = f"""
            <audio controls autoplay="true" style="display: none;" >
            <source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
            </audio>
            """
        st.markdown(
            md,
            unsafe_allow_html=True,)

Hi

If you visualize all the audios in the folder in this way:

import streamlit as st
import base64
from queue import Queue

# Initialize a queue to manage the playback of audio files
audio_queue = Queue()

# Function to play audio files sequentially
def autoplay_audio(audio_file_name: str):
    # Add the audio file name to the queue
    audio_queue.put(audio_file_name)

    # If this is the only audio file in the queue, start playback
    if audio_queue.qsize() == 1:
        play_next_audio()

# Function to play the next audio file in the queue
def play_next_audio():
    # If the queue is not empty
    if not audio_queue.empty():
        # Get the next audio file name from the queue
        audio_file_name = audio_queue.get()
        file_path = f'D:/Users/ES000881/Desktop/GAP/audio/{audio_file_name}.mp3'
        
        # Read the audio file and convert it to base64
        with open(file_path, "rb") as f:
            data = f.read()
            b64 = base64.b64encode(data).decode()

        # Display the audio player using st.audio
        st.audio(data, format='audio/mp3')

        # Remove the played audio file from the queue
        audio_queue.task_done()

        # If there are more audio files in the queue, play the next one
        if not audio_queue.empty():
            play_next_audio()

# Example usage:
autoplay_audio("audio1")
autoplay_audio("audio2")

Queueing seems resonable, but this does not autoplay or is waiting for the first audio to finish before it starts the next.

If it is automatic playback, it is obvious that it is restricted by the browser, and you need to add it to allow :point_down:.


How to achieve continuous playback, I feel powerless, I am a novice.(;′⌒`)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.