加载音频后运行功能 [英] Run function after audio is loaded
问题描述
我想在检查是否下载了音频文件后运行功能.
I want to run a function after checking if an audio file is downloaded.
我的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
我希望在音频文件完成下载后显示已加载的音频"文本.用于检查文件是否已完成下载的代码可能完全是bs,所以请放手吧.
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.
感谢您的帮助!
推荐答案
您甚至没有使用正确的方法检查加载的状态.请参见下面的代码片段.
You are not using the correct even to check the loaded status. See below a snippet that will do that.
您需要使用canplaythrough
事件,这意味着
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.
您正在使用的complete
事件实际上是在以下情况触发的:
The event you are using complete
is actually triggered when
OfflineAudioContext的呈现终止.
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>
有关音频元素的更多信息,请参考 MDN文档
For more on audio elements refer MDN Docs
希望这会有所帮助:)
这篇关于加载音频后运行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!