【问题标题】:How to stop one audio player from playing when I click another - javascript当我单击另一个音频播放器时如何停止播放 - javascript
【发布时间】:2013-05-03 23:38:24
【问题描述】:

我正在为 ipad 创建一个页面。

我在一个页面上有 12 个音频播放器。它们都工作正常,但如果您单击第二个播放器,第一个播放器会继续播放。我以前见过这个问题,但没有一个答案是针对我的代码的。

<script>

function EvalSound(soundobj) {
 var thissound=document.getElementById(soundobj);
  if (thissound.paused)
            thissound.play();
    else
        thissound.pause();
        thissound.currentTime = 0;
}
</script>

玩家自己:

<a href="card3_ipad.php?card=funny" onClick="EvalSound('song1'); return true;"
    target="player"><IMG SRC="images/funnytab.gif" BORDER=0 WIDTH=128 HEIGHT=29>
</A>    
<audio id="song1" style="display: none; width: 0px; height: 0px;"
src="mp3examples/funnyauto.mp3" controls preload="auto" autobuffer>

那么另一个玩家是:

<a href="card3_ipad.php?card=country" onClick="EvalSound('song2'); return true;"
    target="player"><IMG SRC="images/countrytab.gif" BORDER=0 WIDTH=128 HEIGHT=29>
</A>    
<audio id="song2" style="display: none; width: 0px; height: 0px;"
src="mp3examples/countryauto.mp3" controls preload="auto" autobuffer>

任何帮助将不胜感激!

干杯

汤姆

【问题讨论】:

    标签: javascript html audio


    【解决方案1】:

    使用另一个保存当前活跃玩家的变量

    <script>
    var currentPlayer;
    function EvalSound(soundobj) {
    
     var thissound=document.getElementById(soundobj);
     if(currentPlayer  && currentPlayer != thissound) {
          currentPlayer.pause(); 
     }
     if (thissound.paused)
                thissound.play();
        else
            thissound.pause();
            thissound.currentTime = 0;
             currentPlayer = thissound;
    }
    </script>
    

    【讨论】:

    • 感谢您的快速回复!不幸的是,现在什么都没有播放:(
    • 再次谢谢你 :) 这次几乎成功了!如果播放器是第一次使用,它就不起作用。如果它已经启动一次,那么代码就可以工作。如果是第一次播放歌曲,则不会停止前一个播放器。
    • 如果你通过调用 EvalSound 来启动你的第一个播放器,那么它会起作用。但如果你从其他地方启动它,那么你必须将 currentPlayer 设置为当前播放器。
    • 我确实通过调用 EvalSound 来启动第一个播放器,但是当您启动下一个播放器时,两首歌会一起播放。在代码起作用并且它们彼此停止之后,您必须暂停两首歌曲。
    • 我刚刚在 PC 上的浏览​​器上对其进行了测试,非常完美。该问题仅出现在 ipad2 上。我没有 ipad3 来测试它。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多