javascript - HTML 页面上有多个音频文件,一次只需要播放一个

标签 javascript

我有多个音频文件,使用以下 JavaScript 代码单击时会播放:

函数 playSound(el,声音文件) {

          if (el.mp3) {
              if(el.mp3.paused) el.mp3.play();
              else el.mp3.pause();
          } else {
              el.mp3 = new Audio(soundfile);
              el.mp3.play();
          }
      }

问题是,当单击两个时,两个音频文件将同时播放。我需要在单击第二个音频文件时停止播放第一个音频文件。

我需要在这段代码中添加什么。

最佳答案

我还没有使用过 HTML5 的声音 API,所以这只是为了表达我的观点。

所以,就像我在评论中所说的那样,您可以将所有元素添加到全局数组中并像这样暂停它们。

  var audio = [];

  function playSound(el,soundfile) {

    // Pause all 

     if (el.mp3) {
          if(el.mp3.paused) {
              // Pause all sounds
              pauseAllSounds();

              el.mp3.play();

              // Add the sound to the audio array
              audio.push(el);

              // You should probably clean up the audio array too, 
              // so no two identical audio files exists in the array, 
              // but that's up to you! :)
          }
          else el.mp3.pause();
      } else {
          el.mp3 = new Audio(soundfile);
          el.mp3.play();
      }
  }

  function pauseAllSounds(){
    audio.forEach(function(el){
       if(!el.mp3.paused) el.mp3.pause();
    });
  }

关于javascript - HTML 页面上有多个音频文件,一次只需要播放一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088534/

相关文章:

javascript - AngularJS 搜索不起作用

javascript - 在 Javascript 中,如果作为子窗口调用,则使用 focus() 设置文本区域不起作用

javascript - 颜色框和图像调整大小

javascript - 自定义结账字段: Hiding/showing fields with a selector

javascript - Knockout.js:对多个键进行排序

javascript - 如何从 map 返回默认值?

javascript - WPF WebBrowser 通过 IWebBrowser2 界面的静默模式不起作用?

javascript - 如何使用 img HTML 调整输入大小

javascript - 使用 jQuery 消费 JSON

javascript - 使用 AngularJS 更新服务器