预加载多个音频文件 [英] Preload multiple audio files

查看:268
本文介绍了预加载多个音频文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页上只有一个音频控件.我希望使用它来播放多个非常短的音频文件,具体取决于页面的状态.我不希望在播放文件时加载文件.如何在页面加载时加载所有这些文件?

I have a single audio control on my webpage. I wish to use it to play multiple very short audio files depending on the state of the page. I do not wish to load the files as I play them. How do I load all of these files on page load?

以下是我正在做的事情的大致构想:

Here's is a rough idea of what I'm doing:

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>

这篇关于预加载多个音频文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆