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!
JavaScript
x
14
14
1
<tr>
2
<td><strong>Welcome!</strong></td>
3
<td><a><input type="button" value="▶" onclick="play()">
4
<audio id="audio" src="http://www.noiseaddicts.com/samples_1w72b820/3740.mp3"></audio></a>Diluedinpe!
5
</td>
6
</tr>
7
8
<tr>
9
<td><strong>Good Evening</strong></td>
10
<td><input type="button" value="▶" onclick="play()">
11
<audio id="audio" src="http://www.noiseaddicts.com/samples_1w72b820/3719.mp3"></audio>Butuku bulenaga</td>
12
</tr>
13
14
JavaScript
1
7
1
<script>
2
function play() {
3
var audio = document.getElementById("audio");
4
audio.play();
5
}
6
</script>
7
Advertisement
Answer
in simple way you can pass audio tag id in onclick function and then get audio tag by passed id in function:
JavaScript
1
13
13
1
<tr>
2
<td><strong>Welcome!</strong></td>
3
<td><a><input type="button" value="▶" onclick="play('audio1')">
4
<audio id="audio1" src="http://www.noiseaddicts.com/samples_1w72b820/3740.mp3"></audio></a>Diluedinpe!
5
</td>
6
</tr>
7
8
<tr>
9
<td><strong>Good Evening</strong></td>
10
<td><input type="button" value="▶" onclick="play('audio2')">
11
<audio id="audio2" src="http://www.noiseaddicts.com/samples_1w72b820/3719.mp3"></audio>Butuku bulenaga</td>
12
</tr>
13
js:
JavaScript
1
7
1
<script>
2
function play(audioId) {
3
var audio = document.getElementById(audioId);
4
audio.play();
5
}
6
</script>
7