如何在html5/JS中只预加载音频文件的一部分

How to preload only part of a audio file in html5/JS?

本文关键字:加载 音频 文件 一部分 html5 JS      更新时间:2023-09-26

我在一个网页中有多个音频文件。我希望页面一加载就可以播放所有内容,但一次完全预加载所有内容太重,也没用。所以我只想预加载一定量的音频,并在播放完后加载其余的音频(类似于我们在YouTube上看到的行为)。

我如何在HTML5页面上做到这一点(可能使用Javascript)?

您可以尝试一些技巧,比如在onload侦听器中播放文件的前10%。

然而,根据经验,我发现浏览器无论如何都只预加载音频内容的开头。(如果他们预加载任何东西:例如iOS和mobilechrome都拒绝预加载。)例如,在Firefox中,你可以检查HTTP请求,你会发现它们是不覆盖整个文件的部分内容请求。

您可以编辑这些文件,这样您就有了剪切的版本。在页面加载时加载这些文件,然后通过ajax调用加载全尺寸文件。

HTML: 
<div id="myAudioFilesDiv">
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio> 
</div>

js: 
//(document.ready) code
var refresh = true;
    data = {
        'action': 'manage_reports'
        }; 
    var url = 'includes/ajax_reports.php';
    $.ajax({
        type: 'post', 
        cache: false, 
        url: url, 
        data: data, 
        error:function(result)
        {
            $("#myAudioFilesDiv").html('failed to load full sized music files');
        },
        success:function(result)
        {
//load full sizes music files here
            $("#myAudioFilesDiv").html('<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio> ');
            if(refresh) location.reload(); 
        }
    });

还可以看看这篇文章:http://msdn.microsoft.com/en-us/library/ie/gg589489%28v=vs.85%29.aspx。