Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click a button to play sound on Javascript

I would like to make a button play a B-flat scale when clicked. What am I doing wrong?

<!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>
like image 842
Livy Golini Avatar asked Dec 25 '22 13:12

Livy Golini


2 Answers

Use below code, if the melodies are at some other location. In Javascript, provide below:

<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

<button onclick="PlaySound('melody1')"> button1</button>
<button onclick="PlaySound('melody2')"> button2</button>
like image 101
AB Abhi Avatar answered Dec 27 '22 04:12

AB Abhi


Keep it simple (until it works) and try this:

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

Found it at MDN

like image 39
RhinoDevel Avatar answered Dec 27 '22 02:12

RhinoDevel