Web端播放器支持HLS和HTTP-FLV播放协议,本文介绍Web端播放器的开发方法。
背景信息
操作步骤
在HTML代码中引入CDN资源。
阿里云内容分发网络CDN(Content Delivery Network)资源如下:
<link href="//g.alicdn.com/code/lib/video.js/7.9.7/video-js.min.css" rel="stylesheet"> <script src="//g.alicdn.com/code/lib/video.js/7.9.7/video.min.js"></script> <script src="//g.alicdn.com/linkplatform/videojs-plugins/0.0.3??videojs-tech-flv.js,videojs-plugin-hls-compat.js"></script>
配置JavaScript文件。
function getStreamUrl() { return Promise.resolve('...'); // 获取播放地址返回一个promise } function getSourceType(url) { let type = ''; if (/\.flv/.test(url)) { type = 'video/x-flv'; } else if (/\.m3u8/.test(url)) { type = 'application/x-mpegURL'; } else if(/\.mp4/.test(url)) { type = 'video/mp4'; } return type; } function createPlayer(cb) { var videoEl = document.getElementById('videoEl'); var player = videojs(videoEl, { //配置Video.js提供的方法 autoplay: false, muted: true, controls: true, preload: 'none', loop: false, techOrder: ['flv', 'html5'], flv: { reconnInterval: 5000, reconnTimes: 10, getStreamUrl, mediaDataSource: { cors: true, withCredentials: true }, flvConfig: { lazyLoadMaxDuration: 24 * 60 * 60, }, }, html5: { hls: { cacheEncryptionKeys: true, }, }, }, cb); //LinkVisual相关功能 player.on('error', (e) => { console.error('videojs error: ', e); }); player.on('flvError', (e) => { console.error('flv error: ', e.errorInfo); }); var wrappedPlayer = { play: function(loadSource) { if (loadSource) { if (!player.paused()) { player.pause(); } player.reset(); player.removeClass('vjs-paused'); player.addClass('vjs-waiting'); return getStreamUrl().then((url) => { var source = { src: url, type: getSourceType(url) }; player.src(source); player.autoplay(true); player.load(); }); } return player.play(); }, pause: function() { return player.pause(); } } return wrappedPlayer; } //注册插件到Video.js if (!videojs.getTech('flv')) { videojs.registerTech('flv', videojsTechFlv); } if (!videojs.getPlugin('hlsCompat')) { videojs.registerPlugin('hlsCompat', videojsPluginHlsCompat); } const player = createPlayer(function () { player.play(true); });
文档内容是否对您有帮助?