Home > OS >  javascript onload play audio file
javascript onload play audio file

Time:07-26

I have an audio file with a button when i click on it the audio play and when i click again the audio pause i also whant when the page is load the audio play directly without clicking on the button

I tried autoplay in the html but it didn't work

I tried allow="autoplay" also it didn't work

I tried window.addEventListener('load') also it didn't work

I read that i should use muted but also it didn't work

I'm using chrome and firefox

So How can i make this audio work on refresh or on load for the page and when i click in the button the audio will be pause it and when i click again the audio will be paly

I searched on stack overflow but nothing solve my problem

let audio = document.querySelector('.music audio');
let audioBtn = document.querySelector('.music .musicBtn i');

audio.volume = 0.2;

window.addEventListener("load", () => {
  audio.play();
  
});

audioBtn.addEventListener("click", () => {
  if (audio.paused) {
    audio.play();
    audioBtn.classList.add('fa-volume-up');
    audioBtn.classList.remove('fa-volume-mute');
  } else {
    audio.pause();
    audioBtn.classList.add('fa-volume-mute');
    audioBtn.classList.remove('fa-volume-up');

  }
});
.musicBtn {
    background: transparent;
    padding: 1.5rem 2rem;
    font-size: 3rem;
    border: none;
    cursor: pointer;
}
<div >
  <audio id="audio" style="display:none;" src="music/music.mp3" allow="autoplay" controls autoplay loop></audio>
  <button ><i ></i></button>
</div>
<script src="https://kit.fontawesome.com/9e5ba2e3f5.js" crossorigin="anonymous"></script>

CodePudding user response:

You can not, as browsers only allow playing sounds as a consequence of user-interaction. You could try to hijack any click or mouse movement to enable the plaining of sound, but there is no way to really do it on load alone.

https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

CodePudding user response:

You can try manual interaction by clicking on the play button on DOM load so that the audio plays,

if (document.readyState === 'complete') {
   document.getElementById('#playButton').click();
}
  • Related