简体   繁体   English

如何使此JavaScript触发声音文件?

[英]How do I make this JavaScript work to trigger a sound file?

I put this javascript in the head tag: 我将此javascript放在head标签中:

<script language="javascript" type="text/javascript">
function playSound(soundfile) {
document.getElementById("dummy").innerHTML=
"<embed src=\""+soundfile+"\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
</script>

I put the following code in a div half way down the page: 我将以下代码放在页面中间的div中:

<span id="dummy"></span>
<a href="javascript: void(0);" onclick="playSound('singing-bowl.wav');"><img id="bowl"       
src="pics/singing-bowl.gif" height="119" width="157" /></a>

It's not working. 没用 I don't know javascript very well, but this supposedly works from the sources I copied it from. 我不太了解javascript,但这应该可以从我复制它的源中获得。 I've tried it using both an mp3 version and a wav version. 我已经尝试过使用mp3版本和wav版本。 Neither is working for me. 都没有为我工作。

Any clues? 有什么线索吗?

You can try this 你可以试试这个

function playSound(val)
{
   var sound = new Audio(val);
   sound.addEventListener('canplaythrough', function() { 
     // your call back function
       // for example to play the sound
       sound.play();
   }, false);
}

To be more Efficient 更加高效

var sound =null;
var isReady = false;
window.onload = function()
{
   sound = new Audio('singing-bowl.wav');
   sound.addEventListener('canplaythrough', function() { 
        isReady = true;
   }, false);

}
function playSound()
{
    if(isReady)
    sound.play();
}

If you dont have requirements to support old browser i would suggest you use html5, 如果您没有支持旧版浏览器的要求,建议您使用html5,

<audio controls autoplay>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

And please pay attention that different browsers support different types 并且请注意,不同的浏览器支持不同的类型

http://www.w3schools.com/tags/tag_audio.asp http://www.w3schools.com/tags/tag_audio.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM