Autoplay and controls properties for audio and video

Problem:

I have an app with a few audios (OGG bytes-like stored in a db). Works just fine if user press the play button using st.audio(mybytes). But I need this to autoplay, without showing those controls.

I tried to hack the tag using js code, but couldn’t have it done even if using unsafe_allow_html. Probably injection of js is not yet allowed.

string="""
<button onclick='myFunction()'>Try it</button>
<script>function myFunction() {alert('Hello, world!');}</ script >
"""
st.markdown(string, unsafe_allow_html=True)

I then tried to create my own HTML using markdown, but in this case, I can’t use my bytes-like object without prior writing it to disk.

Expected (sth like):

st.audio(mybytes, format='audio/ogg', autoplay=True, controls=False)

Have anyone solved this kind of problem?

Solution:

mymidia_bytes is a blob object stored in my sqlite database [sqlite.Bytes(my_audio_bytes)], loaded to a pandas dataframe (row.Audio).

To autoplay it in the streamlit app:

import base64

mymidia_placeholder = st.empty()

mymidia_str = "data:audio/ogg;base64,%s"%(base64.b64encode(mymidia_bytes).decode())
mymidia_html = """
                <audio autoplay class="stAudio">
                <source src="%s" type="audio/ogg">
                Your browser does not support the audio element.
                </audio>
            """%mymidia_str

mymidia_placeholder.empty()
time.sleep(1)
mymidia_placeholder.markdown(mymidia_html, unsafe_allow_html=True)
1 Like

Hi, I also want to play audio autoplay but, In this case, I need to take audio from a folder, and I’m not familiar with HTML can you provide a soln how to autoplay audio files from a folder?

1 Like

will this work for videos?

Hello,

I tried some of your code and noticed that the autoplay parameters seems to getting stripped from the code in the app, are you seeing the same type of issue. Running Streamlit 1.0.0, tried st.markdown and components.html(). No joy

This issue has been raised by others as well Autoplay option for audio files · Issue #2446 · streamlit/streamlit · GitHub. It’s discouraging to see how it hasn’t been addressed for more than a year.

Since the Audio component from IPython.display module can autoplay audio files, is there a way to incorporate it somehow in streamlit as a workaround until the proper solution for Autoplay option for audio files · Issue #2446 · streamlit/streamlit · GitHub is found?

FYI by default, autoplay is not allowed by browsers. One needs to add special permissions in Browser settings.