How to switch sound playback () pause () with a single button or link?

I have an audio file that plays when I click on the anchor tag. If the anchor tag is clicked again, I want the sound to pause, I just don't know enough about javascript to pull out this other half. I don’t want to change the contents of the attached tag that they click, I just want the sound file to start and pause whenever it clicks on the tag.

This is what I still have, which at least makes the sound file playable:

<audio id="audio" src="/Demo.mp3"></audio> <a onClick="document.getElementById('audio').play()">Click here to hear.</a> 
+6
source share
2 answers

Vanilla Javascript is the way to do what you need.

Note. I noticed comments on another issue with several upvotes for the native js approach and saw that the OP does not have a jquery tag.

So WORKING EXAMPLE :

SOLN 1 : (my initial call using events)

 var myAudio = document.getElementById("myAudio"); var isPlaying = false; function togglePlay() { if (isPlaying) { myAudio.pause() } else { myAudio.play(); } }; myAudio.onplaying = function() { isPlaying = true; }; myAudio.onpause = function() { isPlaying = false; }; 
 <audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto"> </audio> <a onClick="togglePlay()">Click here to hear.</a> 

SOLN 2 : (using the myAudio.paused property based on dandavi comment )

 var myAudio = document.getElementById("myAudio"); function togglePlay() { return myAudio.paused ? myAudio.play() : myAudio.pause(); }; 
 <audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto"> </audio> <a onClick="togglePlay()">Click here to hear.</a> 
+6
source

You can use jQuery to make a switch for this.

 <a id="music-button" style="cursor:pointer;"> <img src="http://i.stack.imgur.com/LT3WE.png"></a> <audio id="playMusic" autoplay> <source src="sound.mp3"> </audio> <script type="text/javascript"> $('#music-button').toggle( function () { document.getElementById('playMusic').play(); }, function () { document.getElementById('playMusic').pause(); } ); </script> 
+1
source

Source: https://habr.com/ru/post/979297/


All Articles