I’m working on an application which will have an automatic text-to-speech feature. I have a piece of text which I’ve converted to speech using google text-to-speech library. I’m aware that we can generate an audio file of the same using st.audio() but here I want the audio to play automatically after it is generated. (without the user having to click any button anywhere).
Any ideas on how to implement this?
Thanks!
Hi @ayanatherate,
You can accomplish this using a similar method to the one you may have come across in this issue by base64 encoding the generated file.
import base64
import streamlit as st
def autoplay_audio(file_path: str):
with open(file_path, "rb") as f:
data = f.read()
b64 = base64.b64encode(data).decode()
md = f"""
<audio controls autoplay="true">
<source src="data:audio/mp3;base64,{b64}" type="audio/mp3">
</audio>
"""
st.markdown(
md,
unsafe_allow_html=True,
)
st.write("# Auto-playing Audio!")
autoplay_audio("local_audio.mp3")
1 Like
I’m a bit late but thanks a lot for the solution. It worked for me perfectly!
One problem I’m facing is that whenever the text to be converted to speech changes, the speech output isnt changing
automatically. I’ve to refresh the page by some way to play the audio file again. Is there a way to resolve that? That would be really helpful!
Thanks!
Hi @ayanatherate, could you share a code snippet that shows this issue? Are you using st.experimental_memo to cache the autoplay_audio function, perhaps?