How to play a sound in javascript?

0

This way.

$( document ).ready(function() {
  var snd = new Audio("alarm.wav");
  snd.play();
});

And he throws me the following error:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

I see another way to do it:

$( document ).ready(function() {
  let embed = $('<embed/>',{
    'src' : 'alarm.wav',
    'autostart' : 'false',
    'width' : '0',
    'height' : '0',
    'id' : 'sound1',
    'enablejavascript' : 'true'
  });
  embed.appendTo($('body'));

  function PlaySound(soundObj) {
    var sound = document.getElementById(soundObj);
    sound.Play();
  }
  PlaySound("sound1");
});

And this other one throws me the following error:

Uncaught TypeError: sound.play is not a function
    
asked by Pablo Contreras 12.09.2017 в 05:48
source

1 answer

1

You could do it this way:

HTML5

<audio id="audio" controls>
<source type="audio/wav" src="audio.wav">
</audio>

CSS

#audio{
display: none
}

Javascript

var audio = document.getElementById("audio");

audio.play();

I hope you serve

    
answered by 12.09.2017 / 06:00
source