单击按钮可在Javascript上播放声音

时间:2015-10-02 17:53:16

标签: javascript html

点击时,我想让按钮播放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>

5 个答案:

答案 0 :(得分:4)

如果旋律位于其他位置,请使用以下代码。 在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>

在HTML正文中:您可以插入

<button onclick="PlaySound('melody1')"> button1</button>
<button onclick="PlaySound('melody2')"> button2</button>

答案 1 :(得分:1)

保持简单(直到它起作用)并尝试:

<audio id="bflat" src="bflat.mp3"></audio>
<button onclick="document.getElementById('bflat').play()">Play!</button>

MDN

找到它

答案 2 :(得分:1)

这有效:

<!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>

答案 3 :(得分:0)

这很简单,尝试使用此HTML调用PlaySound函数

<button onclick="PlaySound()"> B Flat </button>

保持简单!

答案 4 :(得分:0)

<!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>