【问题标题】:stop audio from playing when another audio starts当另一个音频开始时停止播放音频
【发布时间】:2021-08-31 14:42:36
【问题描述】:

此代码可以完美地在单击按钮时播放随机音频文件,这是我想要的。唯一的问题是,当再次单击该按钮时,我希望当前音频停止,这样它就不会在下一个文件上播放。任何关于如何实现这一点的想法将不胜感激!

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<audio id="sound0" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound1" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound2" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>
<audio id="sound3" src="https://s3.amazonaws.com/freecodecamp/simonSound1.mp3" type="audio/mpeg"></audio>

<button id="button">Click To Play</button>
$( document ).ready(function() {
function playSound(){
  var pattern = [],
    tone;
  pattern.push(Math.floor(Math.random() * 4));
  tone = "#sound" + pattern[0];
  //$(tone).trigger('play');  //uncomment to play
  //$(tone).get(0).play();    //uncomment to play
  $(tone)[0].play();          //comment to turn off
}

$("#button").click(playSound);

});

【问题讨论】:

    标签: javascript jquery audio random


    【解决方案1】:
    • 使用声源数组。
    • 使用new Audio() 并播放那个。

    const sounds = [
      "https://s3.amazonaws.com/freecodecamp/simonSound1.mp3",
      "https://s3.amazonaws.com/freecodecamp/simonSound2.mp3",
      "https://s3.amazonaws.com/freecodecamp/simonSound3.mp3",
      "https://s3.amazonaws.com/freecodecamp/simonSound4.mp3"
    ];
    
    const audio = new Audio();
    
    function playSound(){
      const rand = Math.floor(Math.random() * sounds.length);
      audio.src = sounds[rand];
      audio.play();
    }
    
    document.querySelector("#button").addEventListener("click", playSound);
    &lt;button id="button"&gt;Click To Play&lt;/button&gt;

    如果你想听“结束”并播放另一个音频文件,只需使用:

    audio.addEventListener("ended", playSound);
    

    【讨论】:

      【解决方案2】:

      非 jQuery 解决方案:

      var sound0 = document.getElementById("sound0");
      var sound1 = document.getElementById("sound1");
      
      sound1.onplay = function() {
        sound0.pause();
      }
      

      这段代码的作用是,每当sound1 音频开始播放时,它就会暂停sound0 音频。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多