Linking Scatter plot elements to Audio Files

ok, answering my own question…
Not sure if it belongs here, but such an example would have save me a fair bit of time.

Note:

  • I am using a base64 encoding to pass the audio file

Limitation:

  • Play only once (Only work for the first click)
  • sound file seems truncated at the start of the audio (few second for me) so need to have an audiofile long enough (mine is 8 sec)
import dash
import dash_html_components as html
import base64
from dash.dependencies import Input, Output


app = dash.Dash(__name__) 


# Encode the local sound file.
sound_filename = 'path_to_your_file.mp3'  # replace with your own .mp3 file
encoded_sound = base64.b64encode(open(sound_filename, 'rb').read())


app.layout = html.Div(children=[
    html.H1(children='Demo for Audio with Dash'),

    html.Div(children='''
        Click the button to play your local .mp3 sounds.
    '''),


    html.Button(id="button1", children="Click me for sound"),
    html.Div(id="placeholder", style={"display": "none"})])


@app.callback(Output("placeholder", "children"),
              [Input("button1", "n_clicks")],
              )
def play(n_clicks):
    if n_clicks is None:
        n_clicks = 0
    if n_clicks != 0:
        return html.Audio(src='data:audio/mpeg;base64,{}'.format(encoded_sound.decode()),
                          controls=False,
                          autoPlay=True,
                          )


if __name__ == '__main__':
    app.run_server(debug=True)