This post shows how to toggle (play/pause) sound by JavaScript manipulation of
onclick event of a DOM element. Browser support of HTML5 audio tag is a must in
this example.
<!doctype html><html><head><metacharset="utf-8"><title>JavaScript Toggle (Play/Pause) Sound on Click Event of DOM Element</title><metaname="viewport"content="width=device-width, initial-scale=1"></head><body><buttonid="player"type="button"onclick="javascript:toggleSound();">
Click to Toggle Sound
</button><audioid="audio"><sourcesrc="Wat_Metta_Buddha_Qualities.mp3"type="audio/mpeg">
Your browser does not support this audio format.
</audio><scripttype="text/javascript">functiontoggleSound(){varaudioElem=document.getElementById('audio');if(audioElem.paused)audioElem.play();elseaudioElem.pause();}</script></body></html>
When you click on the button element, the sound will be played. If the element
is clicked again, the sound will be paused. To toggle sound like this, a HTML5
audio element is embedded in the HTML document, and not displayed on screen.
Every time the button element is clicked, the toggleSound function will be
executed. The toggleSound function checks if the audio element is paused.
If the audio element is paused, call play() to play sound. Otherwise call
pause() to stop playing.