javascript 按下按钮时播放声音

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18289162/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:21:32  来源:igfitidea点击:

playing sound when the button is pressed

javascripthtmlaudio

提问by Mj Jam

I am trying to make a simple code that if the user clicked the button the sound is played.

我正在尝试编写一个简单的代码,如果用户单击按钮,则会播放声音。

here is the code:

这是代码:

<script>
function play(){
$("body").append("<embed src='play.mp3' autostart='true' loop='false' width='2'    height='0'></embed>");
}
</script>

<form action="" method="post">
<input type="button" onclick="play()" value="click">
</form>

回答by Dragos Sandu

Try this. Should work.

试试这个。应该管用。

<!DOCTYPE html>
<html>
<head>
<script language="javascript">
function playIt()
{
   document.getElementById("embed").innerHTML="<embed src='play.mp3' autostart=true loop=false volume=100 hidden=true>";
   return true;
}
</script>
</head>
<body>
    <form action="" method="post">
        <button type="button" onclick="playIt()">play</button>
        <div id="embed"></div>
    </form>
</body>
</html>