Reputation: 990
I am trying to use multiple sound files in one website. Basically, one that plays when a certain button is clicked, another one when a certain other button is clicked. So far I merely manage to program one button that plays one sound file.
<script type="text/javascript">
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input class="button" type="button" value="PLAY" onclick="play()">
<audio id="audio" src="sound1.mp3" ></audio>
Any advice is greatly appreciated. Cheers.
Upvotes: 1
Views: 700
Reputation: 36642
If you wish to use a single audio
element and a single function you could do something like this:
function playAudio(el) {
var audio = document.getElementById('audio');
var source = el.getAttribute('data-src');
audio.src = source;
audio.play();
}
<audio id="audio"></audio>
<button onclick="playAudio(this)" data-src="http://www.noiseaddicts.com/samples_1w72b820/3740.mp3">
Play drip
</button>
<button onclick="playAudio(this)" data-src="http://www.noiseaddicts.com/samples_1w72b820/3719.mp3">
Play burp
</button>
Upvotes: 1
Reputation: 986
This will play two different sounds depending on what button is clicked:
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function playTwo(){
var audioTwo = document.getElementById("audioTwo");
audioTwo.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<input type="button" value="PLAY" onclick="playTwo()">
<audio id="audio" src="a.mp3" ></audio>
<audio id="audioTwo" src="b.mp3" ></audio>
The sounds will play on top of each other with the above code.
If you want the sound to stop playing when you click a different button with a different sound, then you can do the following:
function play(){
var audio = document.getElementById("audio");
audio.play();
audioTwo.pause();
}
function playTwo(){
var audioTwo = document.getElementById("audioTwo");
audioTwo.play();
audio.pause();
}
Upvotes: 1
Reputation: 1386
In your fiddle, you named your second sound audio2 but played audio : I edited it : https://jsfiddle.net/7a905g5f/
function play2(){
var audio2 = document.getElementById("audio2");
audio2.play();
}
Or even cleaner with only one play function : https://jsfiddle.net/6n0ebrrc/
Upvotes: 0