This is what I wanna do:
I have like 30 buttons. And I want that when click each button, it will play different mp3 file. Like this http://www.soundjig.com/pages/soundfx/beeps.html
I just know how to click 1 button to play 1 audio file like this:
<audio id="mysoundclip" preload="auto">
<source src="ci1.mp3"></source>
</audio>
<button type="button" class="ci">play</button>
<script type="text/javascript">
var audio = $("#mysoundclip")[0];
console.log(audio);
$("button.play").click(function() {
audio.play();
});
</script>
I don't wanna apply all this code to all of the buttons - Is there anyway to do this quickly?
Thank you for reading!
You can use Audio
class provided by JavaScript.
Check out this fiddle.
Here is the snippet.
var baseUrl = "http://www.soundjay.com/button/";
var audio = ["beep-01a.mp3", "beep-02.mp3", "beep-03.mp3", "beep-04.mp3", "beep-05.mp3", "beep-06.mp3", "beep-07.mp3", "beep-08b.mp3", "beep-09.mp3"];
$('button.ci').click(function() {
var i = $(this).attr('id').substring(1); //get the index of button
new Audio(baseUrl + audio[i - 1]).play(); //play corresponding audio
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button id="b1" type="button" class="ci">SOUND</button>
<br>
<button id="b2" type="button" class="ci">SOUND</button>
<br>
<button id="b3" type="button" class="ci">SOUND</button>
<br>
<button id="b4" type="button" class="ci">SOUND</button>
<br>
<button id="b5" type="button" class="ci">SOUND</button>
<br>
<button id="b6" type="button" class="ci">SOUND</button>
<br>
<button id="b7" type="button" class="ci">SOUND</button>
<br>
<button id="b8" type="button" class="ci">SOUND</button>
<br>
<button id="b9" type="button" class="ci">SOUND</button>
<br>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With