how to play a sound in js code example

Example 1: play sound javascript

var audio = new Audio("folder_name/audio_file.mp3");
audio.play();

Example 2: play sound in javascript

<script>
function play() {
  var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
  audio.play();
}
</script>
<button onclick-"play();">PLAY MY AUDIO</button>

Example 3: how to play sound on load js

var sample = document.getElementById("foobar");
sample.play();

Example 4: how play audio js

let myAudioElement = new Audio('audio.mp3');
myAudioElement.addEventListener("canplaythrough", event => {
  /* the audio is now playable; play it if permissions allow */
  myAudioElement.play();
});

Tags:

Html Example