音频播放器只能播放,不会停止播放

时间:2017-12-03 16:50:15

标签: javascript html audio

我试图制作一个简单的音频播放器,但它不能正常工作!

以下是JavaScript:

var audio = document.getElementById("audio");
var isPlaying = false;

function togglePlay(element) {

  element.classList.toggle("playing");

  if (isPlaying) {
    document.getElementById("audio").pause();
    document.getElementById("audio").currentTime = 0;
  } else {
    document.getElementById("audio").play();
  }

}

document.getElementById("audio").onplaying = function() {
  var isPlaying = true;
};

document.getElementById("audio").onpause = function() {
  var isPlaying = false;
};

请帮帮我!

1 个答案:

答案 0 :(得分:0)

var audio = document.getElementById("audio");
// use .paused instead
// var isPlaying = false;

function togglePlay(element) {
  var promise;

  if (!audio.paused) { /* isPlaying */
    audio.pause();
    audio.currentTime = 0;
    element.classList.remove("playing");
  } else {
    // play is not instant, it returns a promise
    promise = audio.play();
    if (promise.then !== undefined) {
        promise.then(function () {
            element.classList.add("playing");
        });
    } else { /* old API */
        element.classList.add("playing");
    }

  }

}

audio.onplaying = function() {
  ;
};

audio.onpause = function() {
  ;
};

请务必将<script>放在<body>

的末尾
        <script>/* put script at the end of body */</script>
    </body>
</html>

确保<audio>的音频源是实际的音频文件。 (不是包含音频的html文件)打开控制台并查看网络请求。