为什么音频有时播放,有时不在同一浏览器中播放?

时间:2014-06-09 19:35:02

标签: javascript html audio browser hosting

我有以下代码,我不确定是什么问题。我们有音频文件的远程主机有问题吗?在Chrome中,有时它会播放,有时它不播放,当它不播放时,并不表示我的浏览器不支持音频格式。

<audio controls id="audio" style="display:none">
    <source src="http://langcomplab.net/Honey_Gatherers_Master.mp3" type="audio/mpeg" />
    Your browser doesn't support this audio format.
</audio>
<button id="button">Play</button>
<script type="text/javascript">

        // run on page load
    var button = document.getElementById('button');
    var audio = document.getElementById('audio');

    var onClick = function() {
        audio.play(); // audio will load and then play
    };

    button.addEventListener('click', onClick, false);
</script>

http://jsfiddle.net/MfU7h/

更新:这真的很奇怪。在源代码部分,我添加

</html> tag for a block in Qualtrics but when I source my code using rich context editor the tags fade away. Any solution to this? 
<html>
<body onload='Qualtrics.SurveyEngine.addOnload'>
<p>The next two stories will be the two stories presented auditorily. Please press the &ldquo;Play Story&rdquo; button now to hear an example auditory story. Be sure to adjust the volume of the device on which you are listening so that you can hear the auditory story clearly.</p>

<p>&nbsp;</p>

<div>
<audio controls="" id="audio1" style="display:none"><source src="http://langcomplab.net/Test_take2.mp3" style="width:50%" type="audio/mpeg" />Your browser doesn&#39;t support this audio format.</audio>
</div>

<div><button name="play" onclick="disabled=true" style="height:25px; width:200px" type="button">Play Story</button>

<p>&nbsp;</p>
</div>
</body>
</html>

enter image description here enter image description here

P.S。:我在onload部分使用了正确的功能吗?

1 个答案:

答案 0 :(得分:2)

在我看来,您需要在页面加载后执行代码。例如。 (修订版)

<body onload='loadAudio'>

<audio controls id="audio" style="display:none">
    <source src="http://langcomplab.net/Honey_Gatherers_Master.mp3" type="audio/mpeg" />
    Your browser doesn't support this audio format.
</audio>
<button id="button">Play</button>

<script type="text/javascript">

function loadAudio() {
    var button = document.getElementById('button');
    var audio = document.getElementById('audio');

    var onClick = function() {
        audio.play(); // audio will load and then play
    };

    button.addEventListener('click', onClick, false);
}
</script>
</body>

我认为你的代码有时而不是其他代码的原因是因为目前它依赖于DOM加载的速度 - 在音频标记完全加载到页面之前javascript可以执行。