vue3+mqtt+flv实时视频的简单使用

76 篇文章 3 订阅

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>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值