简体   繁体   中英

Playing audio file on click again before it's finished playing

I'm making a soundboard-type website that is pretty simple (this is actually my first project). The premise is that a user loads the page, clicks a button, and a sound plays.

The issue I'm having is that if a user clicks button "A", in the x amount of time it takes to play the sound for button "A", clicking button "A" does not initiate another instance of its sound.

So if the sound for button "A" takes 1 second to play and the user clicks 10 times within 1 second, the sound for button "A" only plays once instead of 10 times.

Not sure if this link works...but this is a link to the fiddle? Beware, no audio is attached to the fiddle so sound won't actually play when you click the buttons. https://jsfiddle.net/pmqr9L0s/

This is what my js looks like so far though:

$(document).ready(function(){
    var kickBass1 = new Audio("audio/kickbass1.mp3");
    $(".kickbass1").click(function(){
        kickBass1.play();
    });

    var hihat1 = new Audio("audio/hihat1.mp3");
    $(".hihat1").click(function(){
        hihat1.play();
    });

    var snare1 = new Audio("audio/snare1.mp3");
    $(".snare1").click(function(){
        snare1.play();
    });

    //add record feature later?
    var record = function(){
    }
});

Try moving your variables inside your click handlers, so that you create a new Audio element every time one of your buttons is clicked.

$(document).ready(function(){        
    $(".kickbass1").click(function(){
        var kickBass1 = new Audio("audio/kickbass1.mp3");
        kickBass1.play();
    });    

    $(".hihat1").click(function(){
        var hihat1 = new Audio("audio/hihat1.mp3");
        hihat1.play();
    });    

    $(".snare1").click(function(){
        var snare1 = new Audio("audio/snare1.mp3");
        snare1.play();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM