множественный аудио html: автоматическая остановка другого при воспроизведении текущего

#javascript #html #jquery #audio #html5-audio

#javascript #HTML #jquery ( jquery ) #Аудио #html5-аудио

Вопрос:

У меня есть 2 экземпляра аудио на одной странице. Обработка звука для воспроизведения и паузы не является проблемой. Проблема в том, что когда воспроизводится звук, и я нажимаю кнопку воспроизведения на другом, я не могу заставить другой экземпляр аудио прекратить воспроизведение с изменением значка

Любая помощь будет оценена по достоинству 🙂 спасибо

 $('section .play').click(function(){
    var $this = $(this);

    // starting audio
    var audioID = "sound"   $(this).attr('id');

    $this.toggleClass('active');
    if($this.hasClass('active')){
        $("#"   audioID).trigger('play');       

    } else {
        $("#"   audioID).trigger('pause');
      
    }
}); 
 section {
    display: block;
    margin-bottom: 30px;
    padding: 0 20px;
    text-align: center;
    width: 200px;
    height: 200px;
    position: relative;
}
 
 section .btn {
    background: #ccc;
border: 0 none;
cursor: pointer;
display: block;
height: 60px;
line-height: 60px;
position: absolute;
width: 200px;
z-index: 100;
bottom: 0;
text-align: center;
 }
  section .btn:after {
    content: "play";
    
 }

section .btn.active:after {
    content: "pause";
    
 } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section><img src="https://unsplash.it/g/300?image=29" width="200" height="200" />
<p class="play btn" id="7"></p>
<p><audio id="sound7">
<source src="https://room1015.com/img/cms/MP3/Hanging-out-in-room-1015.mp3" type="audio/mpeg" />
</audio></p>
</section>
<section><img src="https://unsplash.it/g/300?image=29" width="200" height="200" />
<p class="play btn" id="6"></p>
<p><audio id="sound6">
    <source src="https://room1015.com/img/cms/MP3/HOLLYROSE.mp3" type="audio/mpeg" />
</audio></p>
</section> 

Ответ №1:

Я бы перебирал каждую .play кнопку и определял, когда звук приостановлен (или остановлен), если это так, затем приостанавливал / останавливал все возможные воспроизводимые аудио, а затем начинал воспроизведение звука, соответствующего нажатой play кнопке.

При этом вам не понадобятся идентификаторы, поэтому ваш HTML будет менее загроможден.

Это решение будет работать для любого количества аудио на странице

N.B — я добавил также чисто JS-решение.

 //pure JS Version

const playButton = document.querySelectorAll('section .play')

playButton.forEach(el => {
  const currentAudio = el.nextElementSibling.querySelector('audio')

  el.addEventListener('click', e => {
    if (currentAudio.paused) {
      document.querySelectorAll('audio').forEach(el => el.pause())
      currentAudio.play()
      playButton.forEach(el => el.classList.remove('active'))
      e.currentTarget.classList.add('active')
    } else {
      e.currentTarget.classList.remove('active')
      currentAudio.pause()
    }
  })
})

//jQuery Version
//const playButton = $('section .play')

//playButton.each((_, el) => {
//  const currentAudio = $(el).next().find('audio')[0]

//  $(el).on('click', e => {
//    if (currentAudio.paused) {
//    $('audio').each((_, el) => el.pause())
//      currentAudio.play()
//      playButton.removeClass('active')
//      $(e.currentTarget).addClass('active')
//    }
//    else {
//        e.currentTarget.classList.remove('active')
//        currentAudioJs.pause()
//     }
//  })
//}) 
 section {
  display: block;
  margin-bottom: 30px;
  padding: 0 20px;
  text-align: center;
  width: 200px;
  height: 200px;
  position: relative;
}

section .btn {
  background: #ccc;
  border: 0 none;
  cursor: pointer;
  display: block;
  height: 60px;
  line-height: 60px;
  position: absolute;
  width: 200px;
  z-index: 100;
  bottom: 0;
  text-align: center;
}

section .btn:after {
  content: "play";
}

section .btn.active:after {
  content: "pause";
} 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <img src="https://unsplash.it/g/300?image=29" width="200" height="200" />
  <p class="play btn"></p>
  <p>
    <audio>
      <source src="https://room1015.com/img/cms/MP3/Hanging-out-in-room-1015.mp3" type="audio/mpeg" />
    </audio>
  </p>
</section>
<section>
  <img src="https://unsplash.it/g/300?image=29" width="200" height="200" />
  <p class="play btn"></p>
  <p>
    <audio>
      <source src="https://room1015.com/img/cms/MP3/HOLLYROSE.mp3" type="audio/mpeg" />
</audio>
  </p>
</section>