user3263368 user3263368 - 4 months ago 25
jQuery Question

Add a class to div when HTML5 audio file is playing or pause

I am working on a audio player. When the page load audio file starts playing . Everything is fine but when audio file play i want to add a class "playing" to audio play/pause button i have following HTML code

<div class="player">
<audio id="audio" src="audio/testaudio.mp3" autoplay=""></audio>

<div class="btn__play pull-left" id="btnplay">
<i class="play-pause-button"></i>
</div>
</div>

Answer

Attach playing and pause event, and do operations there.

var playBtn = document.getElementById('play');
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
$(playBtn).click(function() {
  if (isPlaying) {
    myAudio.pause()
  } else {
    myAudio.play();
  }
});

myAudio.onplaying = function() {
  isPlaying = true;
  $(playBtn).removeClass('ion-play');
  $(playBtn).addClass('ion-pause');
};
myAudio.onpause = function() {
  isPlaying = false;
  $(playBtn).addClass('ion-play');
  $(playBtn).removeClass('ion-pause');
};
button {
  font-size: 22px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" />

<body>
  <h3>Audio Test: <button id="play" class="ion-play"></button></h3>
  <div>
    <audio id="myAudio" src="http://www.sousound.com/music/healing/healing_01.mp3" preload="auto">
    </audio>

  </div>
</body>

Comments