使用Jquery / Javascript进行多实例音频播放

Track Name :- i run this bitch
By :- DJ Harsha

Track Name :- ai se eu tei pego
By :- DJ perera

Track Name :- Krewella - Live for the night
By :- DJ perera

Track Name :- bella vita
By :- DJ perera

这是我用来让访问者下载或播放/暂停音乐的html。 这些隐藏的输入用于下载曲目。

这是我的javascript播放和暂停音乐。 我从堆栈溢出问题中获取此代码,并相应地修改了它的更改按钮文本

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

上面的脚本完美无缺。 如果用户尝试播放新曲目,它会暂停任何其他音轨。 但是当播放曲目暂停时问题会增加。 除非用户点击另一个进行播放,否则无法恢复。 然后那个轨道(无法恢复的轨道)并被播放。

但是我已经注意到,当我移动轨道id这样的几行时,它会播放并暂停轨道,但它会同时播放多个。

 
Track Name :- ai se eu tei pego
By :- DJ perera

正如我上面提到的那样,根据Stack-overflow发布的答案,我写了这些。我不擅长javascript或jquery。 所以如果你指出我的问题会很好。 我非常欣赏它

尝试类似的东西

 $(function () { var curAudio; $(".playback").click(function (e) { e.preventDefault(); var song = $(this).next('audio')[0]; if (curAudio && song != curAudio && !curAudio.paused) { curAudio.pause(); $(curAudio).prev().html(' Play'); } if (song.paused) { song.play(); curAudio = song; $(this).html(' Stop'); } else { song.pause(); curAudio = undefined; $(this).html(' Play'); } curPlaying = $(this).parent()[0].id; }); }); 

您可以通过在播放新的逻辑元素时将它们作为一个组暂停来简化您的逻辑,而不是存储当前播放audio元素的id

 $(function () { $(".playback").click(function (e) { e.preventDefault(); var $playback = $(this); $('audio').not(this).each(function() { $(this)[0].pause(); }); var audio = $(this).next('audio')[0]; if (audio.paused) { audio.play() $playback.html(' Stop'); } else { audio.pause(); $playback.html(' Play'); } }); });