Oliverater Oliverater - 7 months ago 49
Javascript Question

Pause audio on click and change image of button

I've not found any solution to having a single button change img when clicked, play audio, and then pause and return to original img on click again. I can get the img to swap, and audio to start with the code below, but no joy pausing it.

https://jsfiddle.net/se4xqzsm/
This is my Javascript

function changeImage() {
var image = document.getElementById('player');
if (image.src.match("pauseicon")) {
image.src = "http://igor.gold.ac.uk/~tprat001/fp_html/playicon.png";
} else {
image.src = "http://igor.gold.ac.uk/~tprat001/fp_html/pauseicon.png";
}
}
function play(){
var audio = document.getElementById("audio");

audio.play();

}


HTML


<img id="player" onclick="play();changeImage();" src="http://igor.gold.ac.uk/~tprat001/fp_html/playicon.png" /><audio id="audio" src="http://igor.gold.ac.uk/~tprat001/fp_html/whale.mp3" loop autoloop ></audio>


CSS

#audioplayer{
position:absolute;
z-index: 100;
cursor: pointer;
height: 80px;
width: 80px;
border-radius: 50%;
background-color:#6854e7;

}

Answer

You need to also add the pause() method to your function.

var playing = false;
function action(){
    var audio = document.getElementById("audio");
    if(playing === false){
        audio.play();
        playing = true;
    }else{
        audio.pause();
        playing = false;
    }
}

Run the code snippet below to see it all in action.

#audioplayer {
  position: absolute;
  z-index: 100;
  cursor: pointer;
  height: 80px;
  width: 80px;
  border-radius: 50%;
  background-color: black;
}

#audioplayer:hover {
  -moz-box-shadow: 0 0 20px #6854e7;
  -webkit-box-shadow: 0 0 20px #6854e7;
  box-shadow: 0px 0px 20px #6854e7;
}
<script>
  function changeImage() {
    var image = document.getElementById('player');
    if (image.src.match("pauseicon")) {
      image.src = "http://igor.gold.ac.uk/~tprat001/fp_html/playicon.png";
    } else {
      image.src = "http://igor.gold.ac.uk/~tprat001/fp_html/pauseicon.png";
    }
  }
  var playing = false;

  function action() {
    var audio = document.getElementById("audio");
    if (playing === false) {
      audio.play();
      playing = true;
    } else {
      audio.pause();
      playing = false;
    }
  }

</script>

<div id="audioplayer">

  <img id="player" onclick="action();changeImage();" src="http://igor.gold.ac.uk/~tprat001/fp_html/playicon.png" />
  <audio id="audio" src="http://igor.gold.ac.uk/~tprat001/fp_html/whale.mp3" loop autoloop></audio>

</div>

Comments