For the button to work as Play / Pause, you need to track the current state of the player. It may be:
- didn't start playing
- plays
- paused
- the track finished the game
Below is a clumsy example where the label on the button changes, depending on the state: Play, Playing, Paused, Done:
var el = document.getElementById('btn-play'); var playing = false; // ΡΠ΅ΠΊΡΡΠ΅Π΅ ΡΠΎΡΡΠΎΡΠ½ΠΈΠ΅ ΠΏΠ»Π΅Π΅ΡΠ° var player = new Audio('http://www.html5tutorial.info/media/vincent.mp3'); player.preload = "auto"; player.addEventListener('ended', function(){ // ΡΠ»ΡΡΠ°Π΅ΠΌ ΠΎΠΊΠΎΠ½ΡΠ°Π½ΠΈΠ΅ ΡΡΠ΅ΠΊΠ° el.innerText = "Done"; playing = false; }); el.addEventListener('click', playPause); // ΡΠ»ΡΡΠ°Π΅ΠΌ Π½Π°ΠΆΠ°ΡΠΈΠ΅ Π½Π° ΠΊΠ½ΠΎΠΏΠΊΡ function playPause() { if( playing) { player.pause(); el.innerText = "Paused"; } else { player.play(); el.innerText = "Playing.."; } playing = !playing; }
<link href="https://yastatic.net/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/> <button id="btn-play" class="btn btn-success">Play</button>