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

Solution 1:

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>

Solution 2:

var audioElement= document.getElementById("audio-player");
function togglePlay() {
    if (audioElement.paused) {
        audioElement.play();
    }
    else {
        audioElement.pause();
    }
};

Solution 3:

You could use jQuery to make a toggle 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>

Solution 4:

the myAudio variable has to be inside the function call...It works fine

function togglePlay() {
  var myAudio = document.getElementById("myAudio");
  return myAudio.paused ? myAudio.play() : myAudio.pause();
};
<audio 
id="myAudio" src="https://clubajax.pythonanywhere.com/media/contact/backgroundM.mp3" preload="auto">
</audio>

<input type="button" value="sound" onclick="togglePlay()" />