我正在尝试根据列表中随机生成的颜色来播放声音。列表名称是 gamePattern 始终包含颜色。起初我听到声音,但后来就听不到了。请问我的代码有什么问题吗?
function makeSound (num){
if (num[0] === "blue"){
var blue = new Audio("sounds/blue.mp3");
blue.play();
console.log(num[0])
}else if (num[0] === "green"){
var green = new Audio("sounds/green.mp3");
green.play();
console.log(num[0])
}else if (num[0] === "red"){
var red = new Audio("sounds/red.mp3");
red.play();
console.log(num[0])
}else if (num[0] === "wrong"){
var wrong = new Audio("sounds/wrong.mp3");
wrong.play();
console.log(num[0])
}else if (num[0] === "yellow"){
var yellow = new Audio("sounds/yellow.mp3");
yellow.play();
console.log(num[0])
}
}
console.log(gamePattern[0])
makeSound(gamePattern)
我添加了 console.log 以确保条件始终相同。但声音没有播放。声音的路径也正确
也许你可以试试这个:
function playSound(name) {
var audio = new Audio("sounds/" + name + ".mp3"); // Assuming sound files are in a 'sounds' folder
audio.play();
}