Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to toggle audio play() pause() with one button or link?

I have an audio file that plays when an anchor tag is clicked. If the anchor tag is clicked again, I want the audio to pause, I just don't know enough about javascript to pull this second half off. I don't want to change the content of the anchor tag they click, I just want the audio file to start and pause whenever they click the tag.

This is what I have so far, 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>
like image 679
ExcellentSP Avatar asked Dec 08 '14 23:12

ExcellentSP


People also ask

How do you make a play pause button for audio in HTML?

HTML | DOM Audio pause() Method The HTML DOM Audio pause() Method is used to pause the currently playing audio. To use the audio pause() method, one must use the controls property to display the audio controls such as play, pause, volume, etc, attached on the audio.

How do you pause audio in HTML?

The pause() method halts (pauses) the currently playing audio. Tip: This method is often used together with the play() method. Tip: Use the controls property to display audio controls (like play, pause, seeking, volume, etc, attached on the audio).


1 Answers

A Vanilla Javascript way to do what you required.

Note: I've noticed comments on other question with multiple upvotes for a native js approach and saw the OP has no jquery tag.

So WORKING EXAMPLE:

SOLN 1: (my initial soln using events)

var myAudio = document.getElementById("myAudio");
var isPlaying = false;

function togglePlay() {
  isPlaying ? myAudio.pause() : 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 myAudio.paused property based on dandavi's 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>
like image 93
Iceman Avatar answered Oct 19 '22 23:10

Iceman