前言:hls.js官网:hls.js - npm
一、demo——在HTML中使用
<audio id="audio" controls></audio>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
document.addEventListener("DOMContentLoaded", () => {
const audio = document.getElementById("audio");
const hls = new Hls();
const audioSrc = "https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8";
if (Hls.isSupported()) {
hls.loadSource(audioSrc);
hls.attachMedia(audio);
hls.on(Hls.Events.MANIFEST_PARSED, function () {
audio.play();
});
} else if (audio.canPlayType("application/vnd.apple.mpegurl")) {
audio.src = audioSrc;
audio.addEventListener("canplay", function () {
audio.play();
});
} else {
console.error("HLS is not supported in this browser");
}
});
</script>
二、在项目中使用
1.下载
npm install hls.js --save
# 或者
yarn add hls.js
2. 引入
import Hls from "hls.js";
3.使用
HTML部分:
<!-- 音频播放 -->
<audio ref="audio" controls :src="audioUrl" style="width: 100%"></audio>
js部分:data里初始化:
hls: null
js部分(核心代码)写在对应场景的methods里(下面的都是固定的,不用更改,除了把地址换一下,audioUrl换成你自己的地址,还有可以换掉ref="audio",换成自己的命名后,记得把this.$refs.自定义命名更改):
if (Hls.isSupported()) {
// 实例化hls对象
this.hls = new Hls();
// 绑定视频地址
this.hls.loadSource(this.audioUrl);
// 绑定视频dom
this.hls.attachMedia(this.$refs.audio);
// 绑定事件
this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
this.$refs.audio.play();
});
} else if (this.$refs.audio.canPlayType("application/vnd.apple.mpegurl")) {
this.$refs.audio.src = this.audioUrl;
this.$refs.audio.addEventListener("canplay", () => {
this.$refs.audio.play();
});
}
4.报错分析
如果他出现这样的错误:Uncaught (in promise) DOMException: Failed to load because no supported source was found
导致他不出现数据给函数放到 this.$nextTick里,可能是因为渲染的问题;
this.$nextTick(() => {
if (Hls.isSupported()) {
// 实例化hls对象
this.hls = new Hls();
// 绑定视频地址
this.hls.loadSource(this.audioUrl);
// 绑定视频dom
this.hls.attachMedia(this.$refs.audio);
// 绑定事件
this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
this.$refs.audio.play();
this.audioLoading = false;
});
} else if (
this.$refs.audio.canPlayType("application/vnd.apple.mpegurl")) {
this.$refs.audio.src = this.audioUrl;
this.$refs.audio.addEventListener("canplay", () => {
this.$refs.audio.play();
});
}
});
想要销毁他,这样写:
if (this.hls) {
this.hls.destroy();
this.hls = null;
}
6.场景分析
6.1 如果你是放到弹窗里,那销毁的这部分代码就写在关闭弹窗后。
6.2 如果你是封装个组件,那你销毁的这部分代码就写在beforeDestroy里,核心代码写在mounted里
祝你使用成功,顺便天天开心,吃饱喝足,快乐不愁,超级超级宇宙最有钱!
有问题可以留言,不过我不一定会回,逗你玩,看见就会回,不过我一般看不见,因为不常登陆~