0x00 前言

由于客户网络不稳定,在加载视频的时候 videoJs 经常会爆出 A network error caused the media download to fail part-way.,修复这个问题时候发掘到了这个好东西,在此记录并且分享一下。

由于开发这个项目的时间是 2016 年 11 月,采用的是当时的 videoJs 版本,导致 videoJs 原生自带的 reloadSourceOnError 插件没有发挥出效用,因为这个问题调试了好久。

注意:升级到最新版本的 videoJs 后再参照以下文档

0x01 解决方法

首先初始化一个播放器:

1
var player = videojs('videoExample').ready(function(){});

我们再解决这个问题的时候有两点难题,一个是由于网络环境不可控导致问题很难重现,另一个是问题出现怎么尝试自动重连。

可以通过创建一个名为 createError 的函数去主动抛出异常,代码如下

1
2
3
function createError() {
player.error({code:2});
}

在 videoJs 最新版本中有一个 reloadSourceOnError 插件可以实现抛出异常自动重连(文档中没有更新)。

于是在 issue 中找到了这个插件更新时候的说明:Using the reloadSourceOnError Plugin - Github

解决方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
player.reloadSourceOnError({

// getSource allows you to override the source object used when an error occurs
getSource: function(reload) {
console.log('Reloading because of an error');

// call reload() with a fresh source object
// you can do this step asynchronously if you want (but the error dialog will
// show up while you're waiting)
reload({
src: '{{$VIDEO_URL}}', // 视频重载的源
type: '{{$VIDEO_TYPE}}' // 重载视频的文件类型
});
},

// errorInterval specifies the minimum amount of seconds that must pass before
// another reload will be attempted
errorInterval: 5
});

0x02 相关资料

Using the reloadSourceOnError Plugin - Github

HLS Plugin - Brightcove