Skip to content Skip to sidebar Skip to footer

Run Function After Audio Is Loaded

I want to run a function after checking if an audio file is downloaded. My js: // https://freesound.org/people/jefftbyrd/sounds/486445/ var audioFile = 'https://raw.githubuserconte

Solution 1:

You are not using the correct even to check the loaded status. See below a snippet that will do that.

You need to use the canplaythrough event that means

The browser estimates it can play the media up to its end without stopping for content buffering.

The event you are using complete is actually triggered when

The rendering of an OfflineAudioContext is terminated.

// https://freesound.org/people/jefftbyrd/sounds/486445/
var audioFile = "https://raw.githubusercontent.com/hitoribot/my-room/master/audio/test/test.mp3";

var audioElem = document.querySelector("audio");
var startElem = document.querySelector("button");
var resultScreen = document.querySelector("p");

function checkAudio() {
  audioElem.setAttribute("src", audioFile);
  audioElem.addEventListener('canplaythrough', (event) => {
    resultScreen.innerHTML = "loaded audio";
  });
}

startElem.addEventListener("click", function() {
  checkAudio();
});
<audio controls="controls" src=""></audio>

<button>load audio</button>

<div class="result">
  <h1>Audio file status:</h1>
  <p></p>
</div>

For more on audio elements refer MDN Docs

Hope this helps :)


Solution 2:

You can use the onload event to get notified when the full audio is loaded:

function checkAudio() {
    audioElem.setAttribute("src", audioFile);
    audioElem.onload= ()=>{
        resultScreen.innerHTML = "loaded audio";
    }
}

startElem.addEventListener("click", function(){
    checkAudio();
});

Post a Comment for "Run Function After Audio Is Loaded"