html audio play/pause button

Аудио плейер

Track 1
Track 2

Каждый трек вставляется блоком html разметки

<div class="podcast">
  <button class="audio-btn">
    <img class="play-button" src="/img/icons/play.jpg" alt="Play">
    <img class="pause-button" src="/img/icons/pause.jpg" alt="Pause">
  </button>
  <audio src="/files/audio/audio-1.mp3"></audio>
  <div class="podcast-title">Track 1</div>
</div>

CSS стили

.podcast {
  text-align: center;
}
.audio-btn {
  background: none;
  border: none;
  cursor: pointer;
}
.podcast .pause-button {
  display: none;
}
.podcast.play .pause-button {
  display: inline;
}
.podcast.play .play-button {
  display: none;
}

JS скрипт

Для работы скрипта требуется jQuery

(function($){
    $(function(){

      let currentAudio;
      let isPlaying = false;

      $('.audio-btn').click(function(){
        let audio = $(this).parent().find('audio');
        let audioTag = audio[0];

        let btn = $(this);
        
        if (!isPlaying) { // Если ничего не воспроизводится
          audioTag.play();
          currentAudio = audioTag; 
          isPlaying = !isPlaying;
          $(currentAudio).parent().addClass('play');
        }else{ // воспроизводится
          // Если клик по тому треку, который воспроизводится
          if(currentAudio === audioTag) {
            currentAudio.pause();
            isPlaying = !isPlaying;
            $('.podcast').removeClass('play');
          }else {
            // Переключиться на другой трек
            currentAudio.pause();
            audioTag.play();
            currentAudio = audioTag;
            $('.podcast').removeClass('play');
            $(currentAudio).parent().addClass('play');
          }
        }
      });
    });
  })(jQuery);
Перейти к верхней панели