如何在 Javascript 中预加载声音?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5313646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to preload a sound in Javascript?
提问by Manuel Ignacio López Quintero
I can preload images easily thanks to the onload
function. But it doesn't work with audio. Browsers like Chrome, Safari, Firefox, etc. don't support the onload
functions in the audio tag.
由于该onload
功能,我可以轻松预加载图像。但它不适用于音频。Chrome、Safari、Firefox 等浏览器不支持onload
音频标签中的功能。
How do I preload a sound in Javascript without using JS libraries and without using or creating HTML tags?
如何在不使用 JS 库和不使用或创建 HTML 标签的情况下在 Javascript 中预加载声音?
采纳答案by McKayla
Your problem is that Audio objects don't support the 'load' event.
您的问题是 Audio 对象不支持 'load' 事件。
Instead, there's an event called 'canplaythrough' that doesn't mean it's fully loaded, but enough of it is loaded that at the current download rate, it will finish by the time the track has had enough time to play through.
相反,有一个名为“canplaythrough”的事件并不意味着它已完全加载,但已加载了足够多的事件,以当前下载速率,它将在曲目有足够的时间播放时完成。
So instead of
所以代替
audio.onload = isAppLoaded;
try
尝试
audio.oncanplaythrough = isAppLoaded;
Or better yet.. ;)
或者更好.. ;)
audio.addEventListener('canplaythrough', isAppLoaded, false);
回答by Jonathan Tonge
I tried the accepted answer by tylermwashburn and it didn't work in Chrome. So I moved on and created this and it benefits from jQuery. It also sniffs for ogg and mp3 support. The default is ogg because some experts say a 192KBS ogg file is as good as a 320KBS MP3, so you save 40% on your required audio downloads. However mp3 is required for IE9:
我尝试了 tylermwashburn 接受的答案,但它在 Chrome 中不起作用。所以我继续创建它,它从 jQuery 中受益。它还嗅探对 ogg 和 mp3 的支持。默认值为 ogg,因为一些专家说 192KBS ogg 文件与 320KBS MP3 一样好,因此您可以节省 40% 的所需音频下载费用。但是 IE9 需要 mp3:
// Audio preloader
$(window).ready(function(){
var audio_preload = 0;
function launchApp(launch){
audio_preload++;
if ( audio_preload == 3 || launch == 1) { // set 3 to # of your files
start(); // set this function to your start function
}
}
var support = {};
function audioSupport() {
var a = document.createElement('audio');
var ogg = !!(a.canPlayType && a.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''));
if (ogg) return 'ogg';
var mp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg;').replace(/no/, ''));
if (mp3) return 'mp3';
else return 0;
}
support.audio = audioSupport();
function loadAudio(url, vol){
var audio = new Audio();
audio.src = url;
audio.preload = "auto";
audio.volume = vol;
$(audio).on("loadeddata", launchApp); // jQuery checking
return audio;
}
if (support.audio === 'ogg') {
var snd1 = loadAudio("sounds/sound1.ogg", 1); // ie) the 1 is 100% volume
var snd2 = loadAudio("sounds/sound2.ogg", 0.3); // ie) the 0.3 is 30%
var snd3 = loadAudio("sounds/sound3.ogg", 0.05);
// add more sounds here
} else if (support.audio === 'mp3') {
var snd1 = loadAudio("sounds/sound1.mp3", 1);
var snd2 = loadAudio("sounds/sound2.mp3", 0.3);
var snd3 = loadAudio("sounds/sound3.mp3", 0.05);
// add more sounds here
} else {
launchApp(1); // launch app without audio
}
// this is your first function you want to start after audio is preloaded:
function start(){
if (support.audio) snd1.play(); // this is how you play sounds
}
});
Furthermore: Here is an mp3 to ogg converter: http://audio.online-convert.com/convert-to-oggOr you can use VLC Media player to convert. Check your mp3 bitrate by right-clicking on the mp3 file (in Windows) and going to the file details. Try to reduce by 40% when selecting your new bitrate for your new 'ogg' file. The converter may throw an error, so keep increasing the size until is accepted. Of course test sounds for satisfactory quality. Also (and this applied to me) if you are using VLC Media player to test your audio tracks make sure you set the volume at 100% or below or otherwise you'll hear audio degradation and might mistakenly think it is the result of compression.
此外:这是一个 mp3 到 ogg 转换器:http: //audio.online-convert.com/convert-to-ogg或者您可以使用 VLC 媒体播放器进行转换。通过右键单击 mp3 文件(在 Windows 中)并转到文件详细信息来检查您的 mp3 比特率。为新的“ogg”文件选择新的比特率时,尝试降低 40%。转换器可能会抛出错误,因此请继续增加大小直到被接受。当然,测试声音以获得令人满意的质量。另外(这也适用于我)如果您使用 VLC 媒体播放器来测试您的音轨,请确保将音量设置为 100% 或更低,否则您会听到音频质量下降,并可能错误地认为这是压缩的结果。
回答by Damien Wilson
回答by Luca Filosofi
//Tested on Chrome, FF, IE6
function LoadSound(filename) {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("load-sound").innerHTML = '<embed src="' + filename + '" controller="1" autoplay="0" autostart="0" />';
}
}
xmlhttp.open("GET", filename, true);
xmlhttp.send();
}
Reference
参考
回答by DA.
Remy came up with a solution for iOS that utilizes the sprite concept:
Remy 提出了一个利用 sprite 概念的 iOS 解决方案:
http://remysharp.com/2010/12/23/audio-sprites/
http://remysharp.com/2010/12/23/audio-sprites/
Not sure it directly addresses the preload, but has the advantage that you only need to load one audio file (which is also a drawback, I suppose).
不确定它是否直接解决了预加载问题,但它的优点是您只需要加载一个音频文件(我想这也是一个缺点)。
回答by two7s_clash
Did you try making an ajax request for the file? You wouldn't show/use it until it was all the way loaded.
您是否尝试对文件发出 ajax 请求?在完全加载之前,您不会显示/使用它。
E.g. jQuery: How do you preload sound?(you wouldn't have to use jQuery).
例如jQuery:你如何预加载声音?(您不必使用 jQuery)。