I would like to play different short audio clips on a single page by using different buttons, however the code I have means that all buttons will play only the first .mp3 located in the audio folder regardless of the html code I have that specifies which button will play which audio clip (example below).
Could you help me with the code to figure out where I went wrong?
Thanks!
<tr>
<td><strong>Welcome!</strong></td>
<td><a><input type="button" value="▶" onclick="play()">
<audio id="audio" src="http://www.noiseaddicts.com/samples_1w72b820/3740.mp3"></audio></a>Diluedinpe!
</td>
</tr>
<tr>
<td><strong>Good Evening</strong></td>
<td><input type="button" value="▶" onclick="play()">
<audio id="audio" src="http://www.noiseaddicts.com/samples_1w72b820/3719.mp3"></audio>Butuku bulenaga</td>
</tr>
<script>
function play() {
var audio = document.getElementById("audio");
audio.play();
}
</script>
Advertisement
Answer
in simple way you can pass audio tag id in onclick function and then get audio tag by passed id in function:
<tr>
<td><strong>Welcome!</strong></td>
<td><a><input type="button" value="▶" onclick="play('audio1')">
<audio id="audio1" src="http://www.noiseaddicts.com/samples_1w72b820/3740.mp3"></audio></a>Diluedinpe!
</td>
</tr>
<tr>
<td><strong>Good Evening</strong></td>
<td><input type="button" value="▶" onclick="play('audio2')">
<audio id="audio2" src="http://www.noiseaddicts.com/samples_1w72b820/3719.mp3"></audio>Butuku bulenaga</td>
</tr>
js:
<script>
function play(audioId) {
var audio = document.getElementById(audioId);
audio.play();
}
</script>