当前位置: 首页 > 工具软件 > DPlayer > 使用案例 >

Dplayer中Hls支持小解

公孙栋
2023-12-01

摘要

Dplayer播放器框架从浏览器自身的videoDOM组件继承扩展而来,因此其本身只支持如下三种媒体类型。其他的如m3u8和flv等类型并不支持,需要通过扩展进行。

File FormatMedia Type
MP4video/mp4
WebMvideo/webm
Oggvideo/ogg

而Dplayer文档本身叙述并不十分清晰,因此,本文仅对这类支持做出一些个人见解的描述,如有谬误,欢迎交流改正。

HLS支持的两种写法

写法一:通过script标签提前引入,并在pluginOptions中进行配置

<div id="dplayer"></div>
<script src="hls.min.js"></script>
<script src="DPlayer.min.js"></script>
const dp = new DPlayer({
    container: document.getElementById('dplayer'),
    video: {
        url: 'demo.m3u8',
        type: 'hls',
    },
    pluginOptions: {
        hls: {
            // hls config 见(https://hls-js.netlify.app/api-docs/variable/index.html#static-variable-hlsDefaultConfig)
        // hls参考默认配置
        },
    },
});
console.log(dp.plugins.hls); // Hls 实例

重要:

首先该方法需要利用script标签事先引入hls.js,并确保其位置位于DPlayer.js之前,其主要作用是提前配置window.Hls对象。因为dplayer在检测到video类型为hls之后,会判断当前window对象中是否存在Hls属性,如果没有事先加载,自然无法进行hls文件的读取。(chrome和edge好像都是默认不支持,只有safari默认支持)

case 'hls':
    if (window.Hls) {
        if (window.Hls.isSupported()) {
             const options = this.options.pluginOptions.hls;
             const hls = new window.Hls(options);
             this.plugins.hls = hls;
             hls.loadSource(video.src);
             hls.attachMedia(video);
             this.events.on('destroy', () => {
                  hls.destroy();
                   delete this.plugins.hls;
             });
         } else {
             this.notice('Error: Hls is not supported.');
         }
    } else {
         this.notice("Error: Can't find Hls.");
    }
    break;

注意点:

需要在dplayer之前加载hls.js

需要将视频配置中将视频类型写作hls

写法二:通过video配置中的customType进行自定义

const dp = new DPlayer({
    container: document.getElementById('dplayer'),
    video: {
        url: 'demo.m3u8',
        type: 'customHls',
        customType: {
            customHls: function (video, player) {
                const hls = new Hls();
                hls.loadSource(video.src);
                hls.attachMedia(video);
            },
        },
    },
});

优点

无需通过script标签提前引入,可以通过import标签引入hls.js,在需要的时候进行hls的引用,主要是webpack和vite这类构建工具中可以使用。

注意点

必须在dplayer播放一开始初始化的时候就进行自定义类型的设置,否则在后续使用switchvideo函数播放m3u8视频时会不起作用

 类似资料: