我一直试图制作一个按钮来播放音乐,并在单击时停止播放音频,但是无法使其正常工作。请需要帮助
let audio, playBtn;
playBtn = document.querySelector("#playPauseBtn");
const playPause = () => {
audio = new Audio();
audio.paused = true;
audio.src = "music/amor.mp3";
if (audio.paused === true) {
audio.play();
audio.paused = false;
playBtn.innerHTML = "Pause";
} else if (audio.paused === false) {
audio.pause();
playBtn.innerHTML = "Play";
}
}
playBtn.addEventListener("click", playPause);
答案 0 :(得分:1)
正如@christopher_pk指出的那样,您每次都在创建一个新的音频对象,该对象将在您每次按下按钮时将音频重置为开头。 而是在外部声明音频:
eval
let audio, playBtn;
playBtn = document.querySelector("#playPauseBtn");
audio = new Audio();
audio.paused = true;
audio.src = "https://www.random.org/audio-noise/?channels=2&volume=100&rate=16000&size=8&date=2018-07-06&format=wav&deliver=browser";
const playPause = () => {
if (audio.paused === true) {
audio.play();
audio.paused = false;
playBtn.innerHTML = "Pause";
} else if (audio.paused === false) {
audio.pause();
playBtn.innerHTML = "Play";
}
}
playBtn.addEventListener("click", playPause);