新的音频会预加载声音文件吗? [英] does new Audio preload the sound file?

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

问题描述

我得到一个音频元素并像这样播放声音:

I get an audio element and play the sound like so:

let audio = document.querySelector(`audio[data-key="${e.key}"]`);
audio.play();

但是有时候(我使用的是Chrome)在播放声音时会出现延迟,因此我还添加了以下代码:

However sometimes (I use Chrome) there is initially a delay when I play a sound, so I also added this code:

let audioElems = document.querySelectorAll('audio');
audioElems.forEach(function (audio) {
    new Audio(`./sounds/${audio.dataset.key}.mp3`);
});

起初似乎有所不同,但现在有时又会有所延迟.额外的代码会有所不同吗,会使用 new Audio 实际预加载声音文件吗?

It seemed to make a difference at first but now again sometimes I get the delay. Does the extra code make a difference, will using new Audio actually preload the sound file?

推荐答案

它不一定要预加载它,但是会创建一个HTMLAudioElement,其 preload 属性设置为 auto .
这意味着UA会被告知,如果他们对资源进行了适当的调暗,则应预加载资源,例如,如果使用移动数据,他们可以忽略该资源.

It doesn't necessarily preload it, but it creates an HTMLAudioElement with the preload attribute set to auto.
This means that UAs are told that they should preload the resource if they dim it appropriate, e.g, they could ignore it if on mobile data.

console.log(new Audio)

由于您遇到的问题,已知Chrome 可以最多接受6个并发请求.因此,如果您的 audioElems NodeList包含6个以上的元素,则可能是其中某些元素被延迟到获取第一个元素之前的原因.

Now to your issue, Chrome is known to not accept more than 6 simultaneous requests. So if your audioElems NodeList contains more than 6 elements, that would be the cause for some of them to be delayed until the first ones are fetched.

此外,由于MediaElement中的所有内容都是异步的,因此至少总会有一点延迟.根据您的需求,使用Web Audio API可能会获得更好的结果.

Also, there will always be at least a little delay, since all in MediaElement is asynchronous. Depending on what you are after, you may get better results using the Web Audio API.

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

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