multiple html5 audio players play control

蹲街弑〆低调 提交于 2021-01-29 16:05:44

问题


I have multiple HTML5 audio players on my page, the problem is that when I play both of them they play simultaneously overlapping each other's sound. Basically what I want to do is that one player is playing and another is clicked for play the previous one stops playing.

Following is my html

  <div>
     <audio controls="controls">
         <source src="./public/audio/tiesto.mp3" type="audio/mpeg">
     </audio>
  </div>
  <div>
     <audio controls="controls">
          <source src="./public/audio/123.mp3" type="audio/mpeg">
     </audio>
 </div>

This is my js which I copied from somewhere but not sure how it applies to the audio element.

var curPlaying;
$(function () {
    $(".playback").click(function (e) {
        e.preventDefault();
        var song = $(this).next('audio')[0];
        if (song.paused) {
            if (curPlaying) {
                $("audio", "#" + curPlaying)[0].pause();
            }
            song.play();
            curPlaying = $(this).parent()[0].id;
        } else {
            song.pause();
            curPlaying = null;
        }
    });
});

The guys was using a custom play button whereas I want to use the ausio control and it's built in functionality. Is it possible?


回答1:


Simply added the following javascript to my custom js

window.addEventListener("play", function(evt)
{
    if(window.$_currentlyPlaying && window.$_currentlyPlaying != evt.target)
    {
        window.$_currentlyPlaying.pause();
    } 
    window.$_currentlyPlaying = evt.target;
}, true);


来源:https://stackoverflow.com/questions/52877828/multiple-html5-audio-players-play-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!