mqtt依赖
npm install mqtt --save
flv依赖
npm install --save flv.js
<template>
<video autoplay controls width="800" id="my-video" muted></video>
</template>
<script lang='ts' setup>
import { onMounted, ref } from 'vue';
import flvjs from 'flv.js'
import mqtt from 'mqtt'
const timer = ref()
const flvPlayer = ref()
const client = ref()
const options = {
clean: true, // 保留会话
connectTimeout: 1000, // 超时时间
reconnectPeriod: 1000, // 重连时间间隔
}
// 1、mqtt链接
client.value = mqtt.connect('ws://192.168.0.15:1888/mqtt', options)
const sendHeart = () => {
//参数为:(TOPIC,要发送的参数,第二个参数必须为字符串)
timer.value = setInterval(() => {
client.value && client.value.publish('video/qd_onf/5JGPiszviUeFszG19TzxoZ/heart', JSON.stringify({
uuid: "5JGPiszviUeFszG19TzxoZ"
})
)
}, 1000 * 15)
}
// 2、mqtt连接结果
client.value.on('connect', (e: any) => {
console.log("MQTT连接成功!!!")
// 3、发送主题
client.value.subscribe('video/qd_onf/5JGPiszviUeFszG19TzxoZ/play', {
qos: 0
}, (error: any) => { // qos 为通道
if (!error) {
//4.发送消息,维持视频推流
client.value.publish('video/qd_onf/5JGPiszviUeFszG19TzxoZ/play', JSON.stringify({
uuid: "5JGPiszviUeFszG19TzxoZ", // 设备code
}))
// 5、心跳机制
sendHeart()
} else {
console.log('消息订阅失败')
}
})
})
6、创建视频
const cresteVideo = (id = 'my-video') => {
if (flvjs.isSupported()) {
const videoElement = document.getElementById(id);
flvPlayer.value = flvjs.createPlayer(
{
type: "flv",
isLive: true,
url: 'http://demo.flv'
}
);
flvPlayer.value.attachMediaElement(videoElement)
flvPlayer.value.load()
flvPlayer.value.play()
flvPlayer.value.on(flvjs.Events.ERROR, (err: any) => {
// 如果创建视频失败的话,再次创建
setTimeout(() => {
cresteVideo()
}, 1000);
})
sendHeart()
}
}
// 接收消息处理
client.value.on('message', (topic: any, message: any) => {
console.log('收到来自', topic, '的消息---->>', message)
})
// 断开发起重连
client.value.on('reconnect', (error: any) => {
console.log('正在重连:', error)
})
// 链接异常处理
client.value.on('error', (error: any) => {
console.log('连接失败:', error)
})
onMounted(() => {
cresteVideo()
})
</script>
<style scoped>
</style>