使用JS和JQuery播放和停止声音

时间:2016-05-15 00:56:24

标签: javascript jquery audio pause

我可以使用简单的命令https://github.com/admsev/jquery-play-sound播放声音,但我播放的音频文件大约需要2分钟。我需要一种方法来使用javascript或jquery命令停止/静音音频。有谁知道我怎么做到这一点?我不是真的想要一个停止声音的按钮,除非它是一个常规的html按钮,除了停止声音之外还可以做其他事情。

2 个答案:

答案 0 :(得分:1)

您关联的jQuery playSound库不支持暂停。我认为最好选择一个支持暂停的不同库,这样你就不必自己编写这个功能了。

之前我使用过howler.js库,它对我来说很好用。以下是如何使用howler.js:

<!-- to load the library on the page -->
<script src="howler.js">
// to create and play the sound
var backgroundMusic = new Howl({
  urls: ['music.mp3', 'music.ogg'],
}).play();

// to pause the sound
// (make sure the variable `backgroundMusic` is accessible)
backgroundMusic.pause();

// to stop the sound
backgroundMusic.stop();

答案 1 :(得分:1)

没有jQuery,没有插件,只有浏览器。这是一个播放和暂停一个MP3的按钮。你没有指定你想要一个按钮要做的额外事情,所以我没有为那个单独的按钮添加任何额外的功能。还有什么其他的东西你想要这个单独的按钮吗?

顺便说一句,如果你想让音频停止而不是暂停:

  • <style>块中有一行需要取消注释,还有一行要评论。

  • 您需要取消注释<script>块中的一行。

&#13;
&#13;
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    .play:before {
      content: '\25b6';
    }
    .pause:before {
      content: '\275a\275a';  /*Uncomment this line for pause */
      /* content: '\25a0'; */ /*Uncomment this line for stop */
    }
  </style>

</head>

<body>

  <button id="button" class="play">
    <audio id="audio" src="http://glpjt.s3.amazonaws.com/so/av/pf-righteous.mp3"></audio>
  </button>

  <script>
    var audio = document.getElementById('audio');
    var button = document.getElementById('button');

    button.addEventListener('click', playPause, false);

    function playPause() {
      if (!audio.paused) {
        audio.pause();
        // audio.currentTime = 0; // Uncomment this line for stop
        button.classList.remove('pause');
        button.classList.add('play');
      } else {
        audio.play();
        button.classList.remove('play');
        button.classList.add('pause');
      }
    }
  </script>
</body>

</html>
&#13;
&#13;
&#13;