猿问

加载音频后运行函数

我想在检查是否下载了音频文件后运行一个函数。


我的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();

});

代码笔:https ://codepen.io/carpenumidium/pen/KKPjRLR ? editors = 0011


我希望在音频文件下载完成后显示“加载的音频”文本。检查文件是否已完成下载的代码可能完全是 bs,所以请放轻松。


慕尼黑5688855
浏览 168回答 2
2回答

犯罪嫌疑人X

您甚至没有使用正确的方法来检查加载状态。请参阅下面的代码片段,可以做到这一点。您需要使用表示的canplaythrough事件浏览器估计它可以在不停止内容缓冲的情况下播放媒体直到结束。您正在使用的事件complete实际上是在以下情况下触发的OfflineAudioContext 的呈现终止。// 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() {&nbsp; audioElem.setAttribute("src", audioFile);&nbsp; audioElem.addEventListener('canplaythrough', (event) => {&nbsp; &nbsp; resultScreen.innerHTML = "loaded audio";&nbsp; });}startElem.addEventListener("click", function() {&nbsp; checkAudio();});<audio controls="controls" src=""></audio><button>load audio</button><div class="result">&nbsp; <h1>Audio file status:</h1>&nbsp; <p></p></div>

尚方宝剑之说

您可以使用该onload事件在加载完整音频时获得通知:function checkAudio() {&nbsp; &nbsp; audioElem.setAttribute("src", audioFile);&nbsp; &nbsp; audioElem.onload= ()=>{&nbsp; &nbsp; &nbsp; &nbsp; resultScreen.innerHTML = "loaded audio";&nbsp; &nbsp; }}startElem.addEventListener("click", function(){&nbsp; &nbsp; checkAudio();});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答