So, I'm a complete amateur when it comes to coding, but I still like to fiddle around with it. I'm currently working on a html/jS/PHP based soundboard and I can't figure out how to stop sound from playing when pressing a button to play another one.
<script type="text/javascript" charset="utf-8">
$(function() {
$("audio").removeAttr("controls").each(function(i, audioElement) {
var audio = $(this);
var that = this; //closure to keep reference to current audio tag
$("#doc").append($('<button>'+audio.attr("title")+'</button>').click(function() {
that.play();
}));
});
});
</script>
I hope someone understands that. Thanks in advance. There is also a PHP code to fetch the audio file automatically from the folder to the front end, probably unnecessary info for this problem.
This is not very difficult to do if you use HTML5 which introduced the HTMLAudioElement.
Here is the minimal code for what you are trying to do:
You may also consider libraries like howler.js to help you in the development process.
Below code may help others:
You can stop and reset an audio element by pausing it and setting its current time to
0
. You would need to do this whenever a button is clicked. Example:In case you want to leverage the full power of the Web Audio API, you would probably start building your soundboard similar to this:
Please note that the sound URLs given above must either be on the same domain or available under the same origin policy (see CORS headers).
What you could do, is before start playing a new audio pause all available audio on the page. Something like this.
Instead of adding audio using
<audio>
tag you could use HTMLAudioElement.