运行 音频加载后的函数

Run function after audio is loaded

我想运行检查音频文件是否下载后的功能。

我的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

我希望在音频文件下载完成后显示 "loaded audio" 文本。检查文件是否已完成下载的代码可能完全是废话,所以请放轻松。

感谢您的帮助!

您可以使用 onload 事件在 完整 音频加载时收到通知:

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

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

您没有使用正确的偶数来检查加载状态。请参阅下面的代码片段。

您需要使用 canplaythrough 事件,这意味着

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

您正在使用的事件complete实际上是在

时触发的

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 Docs

希望对您有所帮助:)