近期做了一個功能,是接入一個海康的攝像頭的監控視頻,怎么獲取m3u8的視頻這里就不在敘述了,只說一下怎么將m3u8格式的視頻成功播放
一、m3u8和HLS介紹
1.M3U8文件是指UTF-8編碼格式的M3U文件。M3U文件是記錄了一個索引純文本文件,打開它時播放軟件並不是播放它,而是根據它的索引找到對應的音視頻文件的網絡地址進行在線播放。
2.HLS 與 M3U8 HLS(全稱:Http Live Streaming)是由Apple公司定義的用於實時流傳輸的協議
二、nuxt項目中使用HLS播放m3u8
1.安裝hls.js依賴
可以通過npm安裝依賴 npm install hls.js --save ,也可以通過引入的方式 <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
2.代碼實現
<template>
<section>
<video class="full-height full-width" ref="video" controls></video>
</section>
</template>
<script> let Hls = require('hls.js'); export default { data() { return { hls: '' }; }, mounted() { this.$axios.get('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx').then(res => { this.getStream(res.data); }); }, methods: { videoPause() { if (this.hls) { this.$refs.video.pause(); this.hls.destroy(); this.hls = null; } }, getStream(source) { if (Hls.isSupported()) { this.hls = new Hls(); this.hls.loadSource(source); this.hls.attachMedia(this.$refs.video); this.hls.on(Hls.Events.MANIFEST_PARSED, () => { console.log('加載成功'); this.$refs.video.play(); }); this.hls.on(Hls.Events.ERROR, (event, data) => { // console.log(event, data);
// 監聽出錯事件
console.log('加載失敗'); }); } }, beforeDestroy() { this.videoPause(); } } }; </script>
頁面初始化mounted的時候,獲取到m3u8視頻的鏈接,然后通過getStream()方法加載視頻,也通過videoPause()方法停止視頻播放
嗯,首先要感謝大佬的教導,就醬~~