Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoplay html audio created with javascript

I did this little script that can control the playing of an audio track on a webpage.

var source = "audio/burger.mp3"
var audio = document.createElement("audio");
audio.load()
audio.addEventListener("load", function() {
  audio.play();
}, true);
audio.src = source;



$("#playBtn").click(function() {
  audio.play();
});

$("#pauseBtn").click(function() {
  audio.pause();
});

$("#stopBtn").click(function() {
  audio.pause();
  audio.currentTime = 0;
});
<ul>
  <li>
    <a><i class="fa fa-play" aria-hidden="true" id="playBtn"></i></a>
  </li>
  <li>
    <a><i class="fa fa-pause" aria-hidden="true" id="pauseBtn"></i></a>
  </li>
  <li>
    <a><i class="fa fa-stop" aria-hidden="true" id="stopBtn"></i></a>
  </li>
</ul>

I would like know if there is a way for play the file on the page load. I know this way, It's something really 90s but I have to test something on the page.

like image 268
beer_baron Avatar asked Feb 16 '26 02:02

beer_baron


1 Answers

Add *.autoplay = true; before you load.

 var source = "audio/burger.mp3"
 var audio = document.createElement("audio");
 //
 audio.autoplay = true;
 //
 audio.load()
 audio.addEventListener("load", function() { 
     audio.play(); 
 }, true);
 audio.src = source;
like image 195
radiantstatic Avatar answered Feb 17 '26 14:02

radiantstatic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!