Search code examples
javascriptpythonflask

Audio Not Playing When Button Clicked In Python Flask


I am trying to play an audio sound when I click on Delete button. I have also written the external JavaScript file and linked it with Flask.

index.html

<a href="/delete/{{todoitem.item_id}}" class="btn btn-danger" onclick="playDelSound()">Delete</a>

app.js

function playDelSound() {
        var delSound = new Audio("/static/delete.mp3");
        delSound.play();
}

But when I click the Delete button, the sound is not playing.


Solution

  • When you click link then web browser reloads page and it removes from memory code which should play sound.

    You would have to catch link

    <a href="javascript:void(0);" onclick="sound('{{item}}')">JAVASCRIPT LINK</a>
    

    play sound and redirect/reload page after sound.

    function sound(item) {
        var audio = new Audio('/static/audio_file.mp3');
        audio.onended = function() { window.location.href="/delete/" + item; }
        audio.play();
    }
    

    Minimal working code

    from flask import Flask, render_template_string
    
    app = Flask(__name__)
    
    @app.route('/')
    def index():
        return render_template_string('''
    <a href="/" onclick="sound()">NORMAL LINK</a><br>
    
    <a href="javascript:void(0);" onclick="sound('{{item}}')">JAVASCRIPT LINK</a>
    
    <script>
    function sound(item) {
        //alert("SOUND");
        var audio = new Audio('/static/audio_file.mp3');
        // reload after audio 
        audio.onended = function() { window.location.href="/delete/" + item; }
        audio.play();
    }
    </script>
    ''', item="somevalue")
    
    app.run()