当在 chrome 中播放音频时,当在播放调用之前未调用 audio.src 时,我遇到问题。不过firefox可以正常播放。有人可以建议吗?下面是 fiddle 链接 -
http://jsfiddle.net/vn215r2d/1/
还可以在这里找到代码 -
<html>
<head>
<script language="javascript">
var audioo = document.createElement("audio");
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
audioo.play();
}
function playAgain() {
audioo.play(); // doesn't work in chrome :(
}
</script>
</head>
<body>
<button type="button" onClick="newCall()">New Captcha Call</button>
<br>
<button type="button" onClick="playAgain()">Replay Captcha</button>
</body>
</html>
最佳答案
更新
哦,哇,显然是由于在重写 src 之前audio.currentTime 不可写。这是你可以做的并且它确实有效:
function newCall() {
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
// make all audio attributes writeable again by resetting the src
audioo.src = audio.src;
}
答案需要一些谷歌搜索,但我从这里得到了它:https://stackoverflow.com/a/14850353
原版
我在 Chrome 上进行了测试,重置了音频位置,效果很好。首先暂停是最安全的,但无论哪种方式都有效。
var audioo = document.createElement("audio");
// Lets add an event listener to play when we are ready to start playing
audioo.addEventListener("canplaythrough", function(){
audioo.play();
}, false);
function newCall() {
audioo.src = "";
audioo.src = "http://xx.xx.xx.xx:8181/api/captcha/sound";
}
function playAgain() {
// Let's check if we are ready enough to play
if(audioo.readyState === 4){
audioo.pause(); // first pause
audioo.currentTime = 0; // then reset
audioo.play(); // then play
} else {
// else inform us that we are not ready to play yet.
alert("Audio not ready yet.");
}
}
这里有两个有趣的资源可以提供帮助:
关于javascript - audio.play() html 标签无法在 chrome 中播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26545911/