利用hls.js实现ios端和安卓端视频直播fls流播放。
<template>
<div id="app">
<video id="hlsVideo" ref="hlsVideo" controls preload="true"></video>
</div>
</template>
<script>
import Hls from 'hls.js'
import { videlApi } from '@/api/carManage'
export default {
props: {
id: {
type: String,
default: '1',
},
},
name: 'dHelp',
data() {
return {
hls: '',
}
},
watch: {
id(val) {
console.log('id', val)
this.getVide()
},
},
methods: {
destroyHls: function () {
if (this.hls) {
this.$refs.hlsVideo.pause()
this.hls.destroy()
this.hls = null
}
},
loadVideoFn: function (url) {
console.log('url1', url)
if (!url) {
return
}
console.log('2', 2)
if (Hls.isSupported()) {
this.hls = new Hls()
this.hls.loadSource(url) //url是本项目地址
//这下面的url可以随意其它fls流直播地址
// this.hls.loadSource(
// '//sf1-cdn-tos.huoshanstatic.com/obj/media-fe/xgplayer_doc_video/hls/xgplayer-demo.m3u8',
// ) // CCTV1直播源
//判断是否为安卓
this.hls.attachMedia(this.$refs.hlsVideo)
this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
console.log('加载成功')
this.$refs.hlsVideo.play()
})
this.hls.on(Hls.Events.ERROR, (event, data) => {
// console.log(event, data);
// 监听出错事件
console.log('加载失败')
})
//判断是否为IOS
} else if (this.$refs.hlsVideo.canPlayType('application/vnd.apple.mpegurl')) {
this.$refs.hlsVideo.src = url || ''
console.log('苹果src', this.$refs.hlsVideo)
this.$refs.hlsVideo.addEventListener('loadedmetadata', () => {
this.$refs.hlsVideo.play()
console.log(' this.$refs.hlsVideo', this.$refs.hlsVideo)
})
// this.$refs.hlsVideo.addEventListener('loadedmetadata', function () {
// this.$refs.hlsVideo.play()
// console.log(' this.$refs.hlsVideo', this.$refs.hlsVideo)
// })
}
console.log('url2', url)
},
//获取视频
getVide() {
if (!this.id) {
return
}
let params = {
deviceId: this.id,
communityName: '深业新岸线',
}
console.log('params', params)
videlApi(params).then((res) => {
if (res.data.data) {
console.log('res.data.data.hls', res.data.data.hls)
let src = res.data.data.hls.replace('http:', '')
console.log('src:', src)
this.loadVideoFn(src)
}
})
},
},
computed: {},
created: function () {
let _this = this
_this.$once('hook:beforeDestroy', () => {
_this.destroyHls()
})
},
mounted() {
this.getVide()
},
components: {},
}
</script>
<style lang="scss" scoped>
#hlsVideo {
width: 100%;
height: 100%;
border: none;
}
</style>