如何检查HTML5音频是否已达到不同的错误

Nea*_*lis 21 html javascript audio html5

具体来说,如果206个音频请求中的一个失败并且缓冲停止,是否有办法检测该状态?或者我是否应该通过比较缓冲的金额与过去的金额来检查缓冲是否停止?

另外,我如何检查指定的源是否失败,您是否可以将其指向另一个源?

Tom*_*duy 33

1.具体来说,如果其中一个音频请求失败并且缓冲停止,是否有办法检测该状态?

是的,有几种方法可以做到这一点!但是,如果要捕获错误类型,可以将错误事件侦听器附加到源:

$('audio').addEventListener('error', function failed(e) {
   // audio playback failed - show a message saying why
   // to get the source of the audio element use $(this).src
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('A network error caused the audio download to fail.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('The audio playback was aborted due to a corruption problem or because the video used features your browser did not support.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('The video audio not be loaded, either because the server or network failed or because the format is not supported.');
       break;
     default:
       alert('An unknown error occurred.');
       break;
   }
 }, true);
Run Code Online (Sandbox Code Playgroud)

你能把它指向另一个来源吗?

在错误处理函数内部,您可以使用srcaudio元素的属性更改源:

var audio = $(this);
audio.src = "new-audio-file.mp3";
audio.load();
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用以下语法将多个源添加到同一音频标记:

<audio>
    <source id="audio_player_ogv" src="test.ogv" type="audio/ogg" />
    //In case that you can't load the ogv file it will try to load test.mp3
    <source id="audio_player_mp3" src="test.mp3" type="audio/mpeg" />
</audio>
Run Code Online (Sandbox Code Playgroud)

3.关于管理多个音频文件

如果您打算管理206个音频文件,我建议您使用插件.我已经使用SoundManager2一段时间了,它非常好!