6

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

 2 years ago
source link: https://siongui.github.io/2012/10/12/javascript-toggle-sound-onclick/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

Updated: February 25, 2015

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
<!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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK