单击按钮以在 Javascript 上播放声音
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32913026/
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
Click a button to play sound on Javascript
提问by Livy Golini
I would like to make a button play a B-flat scale when clicked. What am I doing wrong?
我想让一个按钮在点击时播放 B-flat 音阶。我究竟做错了什么?
<!DOCTYPE html>
<html>
<head>
<script>
function PlaySound() {
alert("hello");
var bflat = new audio();
bflat.src = "bflat.mp3";
document.getElementById(bflat);
bflat.Play();
}
</script>
</head>
<body>
<audio id="bflat"> </audio>
<button onclick="PlaySound"> B Flat </button>
</body>
</html>
回答by AB Abhi
Use below code, if the melodies are at some other location. In Javascript, provide below:
如果旋律在其他位置,请使用以下代码。在 Javascript 中,提供以下内容:
<script>
function PlaySound(melody) {
alert("On Press of "+melody);
var path = "path\to\melody\"
var snd = new Audio(path + melody + ".mp3");
snd.play();
}
</script>
In HTML body: you can insert
在 HTML 正文中:您可以插入
<button onclick="PlaySound('melody1')"> button1</button>
<button onclick="PlaySound('melody2')"> button2</button>
回答by RhinoDevel
回答by Patrik Fr?hler
This works:
这有效:
<!DOCTYPE html>
<html>
<head>
<script>
var bflat = new Audio();
bflat.src = "bflat.mp3";
function PlaySound() {
bflat.play();
}
</script>
</head>
<body>
<audio id="bflat"> </audio>
<button onclick="PlaySound()"> B Flat </button>
</body>
</html>
回答by victorfern
This is very simple, try to call PlaySound function using this HTML
这很简单,尝试使用此 HTML 调用 PlaySound 函数
<button onclick="PlaySound()"> B Flat </button>
Keep it simple!
把事情简单化!
回答by BartK_97
<!DOCTYPE html>
<html>
<body>
<audio id="myAudio">
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<p>Click the buttons to play or pause the audio.</p>
<button onclick="playAudio()" type="button">Play Audio</button>
<button onclick="pauseAudio()" type="button">Pause Audio</button>
<script>
var x = document.getElementById("myAudio");
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
</script>
</body>
</html>