以下代码可在除 Safari 之外的所有浏览器上按预期工作(Windows 7 使用 5.1.7 版)。
var texto01 = document.getElementById("texto01");
texto01.onkeyup = function(tecla){
if(tecla.keyCode == 13){ //If Enter is keyup
if((valorAnt[0] != texto01.value) && (texto01.value != "")){ //Check to see if answer has changed and field is not empty
valorAnt[0] = texto01.value; //Since value has change, set it to be new previous answer
if(texto01.value == "5747"){ //Correct answer user has to type
ctx.clearRect(739, 57, 35, 35);
ctx.drawImage(bienImg, 739, 57); //Tick image
var cBien = Math.ceil(Math.random()*2); //There are two audio files that can be played if answer is correct
var cSonidoB = "bien" + cBien;
document.getElementById(cSonidoB).play(); //play the "random" audio for right answer
}
else{ //Answer is wrong
ctx.clearRect(739, 57, 35, 35);
ctx.drawImage(malImg, 739, 57); //X mark image
var cMal = Math.ceil(Math.random()*3); //There are three audio files that can be played if answer is wrong
var cSonidoM = "mal" + cMal;
document.getElementById(cSonidoM).play(); //play the "random" audio for wrong answer
}
}
}
}//texto01
所有的音频标签都是这样声明的:
<audio id = "mal1" preload = "auto">
<source src="Sounds/mal01.ogg" type="audio/ogg"></source>
<source src="Sounds/mal01.mp3" type="audio/mpeg"></source>
</audio>
我尝试了以下但没有成功:1)将MP3源放在OGG之前。2) 将类型更改为“音频/mp3” 3) 删除选择要播放的音频并直接分配要播放的音频 ID 的“随机”部分。