我是新来的,我的问题是我试图用onclick事件播放音乐或其他声音,当我试图停止这个声音时,问题就开始了,我希望声音停止,但是声音再次响起,这里是javascript代码:
const playToPause = document.getElementById("play-song");
// main audio functions
function playSound() {
const audio = new Audio("track_path");
addEventListener("click", _ => {
switch (playToPause.value) {
case "pause":
audio.play();
playToPause.value = "play";
break;
case "play":
audio.pause();
playToPause.value = "pause"
}
console.log(playToPause.value);
});
}; 这是按钮元素
<button id="play-song" value="pause" onclick="playSound()" class="fa-solid fa-play fa-3x action-buttons"></button>我以前试过用if...else if,句子,然后我用一个转换语句来改变它,认为问题在if...else if上。
稍后,我使用console.log查看按钮的值,并在第一次单击该按钮时得到:浏览器控制台作为代码标记,带有"`")
控制台显示:play jquery.client.js:16
但是,如果我再次点击按钮,停止声音,它检测为双击。
控制台显示:
play jquery.client.js:16 (The first click)
pause jquery.client.js:16
play jquery.client.js:16对不起,对于我的英语不好,我希望大家能提前帮忙谢谢:)
发布于 2022-03-27 12:44:19
您的问题是,每次函数执行时都要重新定义audio变量,结果是audio.play()或audio.pause()正在播放或暂停刚刚创建的声音。它对以前玩过的任何游戏都没有任何作用。
要修复,只需将audio的定义移出函数。
此外,正如@Ivar在他的评论中说的那样,您的addEventListener不应该在函数中,或者每次添加新的侦听器。由于按钮上的内联onclick属性,每次单击按钮时,您的函数都将运行。
因此,将代码更改为:
const playToPause = document.getElementById("play-song");
const audio = new Audio("track_path");
// main audio functions
function playSound() {
switch (playToPause.value) {
case "pause":
audio.play();
playToPause.value = "play";
break;
case "play":
audio.pause();
playToPause.value = "pause"
}
console.log(playToPause.value);
}; 发布于 2022-03-27 13:06:53
<!-- User Audio Tag -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<audio id="audio-tag">
<source src="./partham-ganesh-besado-re.mp3" type="audio/ogg">
<source src="./partham-ganesh-besado-re.mp3" type="audio/mpeg">
</audio>
<button onclick="play()" type="button">Play</button>
<button onclick="pause()" type="button">Pause</button>
<script>
var audio = document.getElementById("audio-tag");
function play() {
audio.play();
}
function pause() {
audio.pause();
}
</script>
</body>
</html>https://stackoverflow.com/questions/71636381
复制相似问题