[JavaScript] Toggle (Play/Pause) Sound on Click Event of DOM Element


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.

Demo

Source Code for Demo:

toggle.html | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Toggle (Play/Pause) Sound on Click Event of DOM Element</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<button id="player" type="button"
  onclick="javascript:toggleSound();">
  Click to Toggle Sound
</button>
<audio id="audio">
  <source src="Wat_Metta_Buddha_Qualities.mp3" type="audio/mpeg">
Your browser does not support this audio format.
</audio>

<script type="text/javascript">
function toggleSound() {
  var audioElem = document.getElementById('audio');
  if (audioElem.paused)
    audioElem.play();
  else
    audioElem.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.


References:

[1]HTML Audio/Video DOM Reference
[2]HTML5 Audio
[3]Introduction to the HTML5 audio tag javascript manipulation
[4][JavaScript] Play Sound on Click Event of DOM Element
[5][Golang] GopherJS DOM Example - Play Sound on Click Event
[6][Golang] GopherJS DOM Example - Toggle (Play/Pause) Sound on Click Event