问题
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.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);
if (audioElem.complete) {
resultScreen.innerHTML = "loaded audio";
}
}
startElem.addEventListener("click", function(){
checkAudio();
});
Codepen: https://codepen.io/carpenumidium/pen/KKPjRLR?editors=0011
I want the "loaded audio" text to be displayed, after the audio file has completed downloading. The code to check if the file has completed downloading might be utter bs so please go easy on me.
Thanks for your help!
回答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 :)
回答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();
});
来源:https://stackoverflow.com/questions/58180304/run-function-after-audio-is-loaded