html - 预加载多个音频文件

标签 html

我的网页上只有一个音频控件。我希望根据页面状态使用它来播放多个非常短的音频文件。我不想在播放文件时加载它们。如何在页面加载时加载所有这些文件?

这是我在做什么的粗略想法:

http://jsfiddle.net/L0c9ccx9/20/

audio.src = ...;
audio.load();
audio.play();

最佳答案

var audioFiles = [
    "http://www.teanglann.ie/CanC/nua.mp3",
    "http://www.teanglann.ie/CanC/ag.mp3",
    "http://www.teanglann.ie/CanC/dul.mp3",
    "http://www.teanglann.ie/CanC/freisin.mp3"
];
    
function preloadAudio(url) {
    var audio = new Audio();
    // once this file loads, it will call loadedAudio()
    // the file will be kept by the browser as cache
    audio.addEventListener('canplaythrough', loadedAudio, false);
    audio.src = url;
}
    
var loaded = 0;
function loadedAudio() {
    // this will be called every time an audio file is loaded
    // we keep track of the loaded files vs the requested files
    loaded++;
    if (loaded == audioFiles.length){
    	// all have loaded
    	init();
    }
}
    
var player = document.getElementById('player');
function play(index) {
    player.src = audioFiles[index];
    player.play();
}
    
function init() {
    // do your stuff here, audio has been loaded
    // for example, play all files one after the other
    var i = 0;
    // once the player ends, play the next one
    player.onended = function() {
    	i++;
        if (i >= audioFiles.length) {
            // end 
            return;
        }
    	play(i);
    };
    // play the first file
    play(i);
}
    
// we start preloading all the audio files
for (var i in audioFiles) {
    preloadAudio(audioFiles[i]);
}
<audio id="player"></audio>

关于html - 预加载多个音频文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31060642/

相关文章:

javascript - 数字的表单验证

javascript - Fullpage js模糊水平幻灯片之间的过渡

javascript - 使用 Javascript 动态传递点击的 anchor 标记名称

javascript - 将函数/样式应用于每个 each() 迭代

javascript - jQuery 代码省略 iframe 源的顶部和底部部分

html - CSS 宽度 100% 未按预期工作

javascript - IE 对 HTMLDocument 和 HTMLElement 有什么看法

javascript - 在 Canvas 中以 % 宽度居中圆圈

html - 如何在 VSCode 中将 html 属性格式化为垂直列表

javascript - 当文本区域未处于焦点时从屏幕上删除下拉菜单