Reputation: 9
Ok so I understand basic javascript and i'm trying to make a soundboard type of app. I have the buttons on the page but the second button is pulling the audio file for the first button. I've tried putting the buttons in diferent paragraphs, divs, and a bunch of other things but both buttons are playing the exact same sound when different audio files are linked. Please help!
<!DOCTYPE HTML>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play()">
<audio id="audio" src="audio/semipro.MP3" ></audio>
<input type="button" value="PLAY 2" onclick="play()">
<audio id="audio" src="audio/hit.MP3" ></audio>
</body>
</html>
Upvotes: 0
Views: 4508
Reputation: 31
An ID is unique for each element in an HTML page. Don't give one ID for two different elements. You can have the same class but not same IDs ever.
Upvotes: 0
Reputation: 441
Don't use duplicate IDs. You only need one audio element you can change the src attribute in your click function. Also input elements should only be within forms, use button elements instead:
<!--HTML-->
<audio id="audio"></audio>
<button onclick="play('file1.mp3')">Play Sound 1</button>
<button onclick="play('file2.mp3')">Play Sound 2</button>
--
//JS
function play(sound){
var audio = document.getElementById("audio");
audio.setAttribute('src', sound);
audio.play();
}
Working example: http://jsfiddle.net/Nillervision/et2tb7e0/
Upvotes: 0
Reputation: 4830
You shouldn't have two elements with the same id, they should always be unique.
Suggestion:
Your play
method could take an id
parameter, which should be the same id
as the one in the audio
tag that the button should play.
Possible Solution:
<!DOCTYPE HTML>
<html>
<head>
<title>Audio</title>
</head>
<body>
<script>
function play(element){
var audio = document.getElementById(element);
audio.play();
}
</script>
<input type="button" value="PLAY" onclick="play('audio1')">
<audio id="audio1" src="audio/semipro.MP3" ></audio>
<input type="button" value="PLAY 2" onclick="play('audio2')">
<audio id="audio2" src="audio/hit.MP3" ></audio>
</body>
</html>
Upvotes: 3