Reputation: 273
Im having trouble with more than 1 play/pause button in a same code, i have a table where there is a button and then the song name on cell to the right.
the button works perfectly, here is the code(got it from internet):
<script language="javascript">
function play_pause() {
var myAudio = document.getElementById("myAudio");
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
</script>
And the audio part
<html>
<table>
<tr>
<td>
<audio preload="none" id="myAudio" src="music.mp3" type="audio/mpeg"</audio>
<img src="play.png" width=30 height=30 border="0" onclick="play_pause()";>
</td>
</tr>
<tr>
<td>
<audio preload="none" id="myAudio" src="music2.mp3" type="audio/mpeg"</audio>
<img src="play.png" width=30 height=30 border="0" onclick="play_pause()";>
</td>
</tr>
</table>
</html>
So whenever i play any button on my web, it starts the first song and if i try to play another its like im unpausing the first one (actually only play the first one, even when i sourced another) Im pretty sure is because of the lack of code in my function, and because both audio tags reference the same ID, but however, what do i exactly have to implement on my script to make my page works fine? I've tried a lot of things but can't really make it works as i want. I'd highly appreciate some advices, thanks in advance.
Ps: Is not necessary for me now, but if with the code i can also get a change icon for my audio, i mean when "onclick" it i change to a pause icon, thanks!
Upvotes: 1
Views: 2728
Reputation: 8184
You may Put difference between objects like this
function play_pause(player) {
var myAudio = document.getElementById(player);
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
And
<html>
<table>
<tr>
<td>
<audio preload="none" id="myAudio1" src="music.mp3" type="audio/mpeg"</audio>
<img src="play.png" width=30 height=30 border="0" onclick="play_pause('myAudio1')";>
</td>
</tr>
<tr>
<td>
<audio preload="none" id="myAudio2" src="music2.mp3" type="audio/mpeg"</audio>
<img src="play.png" width=30 height=30 border="0" onclick="play_pause('myAudio2')";>
</td>
</tr>
</table>
EDITS: Use this loop for more than 4 players
var songs=['song1.mp3','song2.mp3','song3.mp3','song4.mp3'];
var players="<table>";
for(var i=0;i<songs.length;i++){
players+='<tr>
<td>
<audio preload="none" id="myAudio_'+i+'" src="'+songs[i]+'" type="audio/mpeg"</audio>
<img src="play.png" width=30 height=30 border="0" onclick="play_pause(\'myAudio_'+i+'\')";>
</td>
</tr>';
}
players+="</table>"
document.getElementById('myTable').innerHTML=players;
and your html
<body> <div id='myTable'></div> </body>
Upvotes: 2