Newer
Older
IntegratedFront / src / views / page / video / components / wsPlayer.vue
<!--
  Description: 视频播放-img-ws
  Author: 李亚光
  Date: 2024-11-11
 -->
<script lang="ts" setup name="VideoPlayer">
const $props = defineProps({
  id: {
    type: String,
    required: true,
  },
  status: {
    type: String,
    default: '',
  },
})
const publicPath = window.location.href.split('#')[0]
const src = ref(`${publicPath}/image/normal.png`)
const webSocket = ref()
watch(() => $props.id, (newVal) => {
  if (!newVal) {
    src.value = `${publicPath}/image/nodata.png`
    return
  }
  if ($props.status === '离线') {
    src.value = `${publicPath}/image/offline.png`
    return
  }
  if ($props.status !== '在线') {
    src.value = `${publicPath}/image/normal.png`
    return
  }
  if (Number(newVal)) {
    console.log(newVal, 'newVal')
    src.value = `${publicPath}/image/loading.gif`
    // webSocket.value = new WebSocket('ws://192.168.10.135:9000/api/display/ws/video/8')
    webSocket.value = new WebSocket(`ws://${window.localStorage.getItem('IntegratedFront')?.split('://')[1]}/api/display/ws/video/${newVal}`)
    webSocket.value.onmessage = function (event: any) {
      // 从服务器接收二进制图像数据并转换为 Blob 对象
      const blob = new Blob([event.data], { type: 'image/jpeg' })
      // 生成图像 URL 并更新 <img> 标签
      src.value = URL.createObjectURL(blob)
    }
    // webSocket.value.onclose = function () {
    //   console.error('WebSocket 连接已关闭')
    //   src.value = `${publicPath}/image/normal.png`
    // }

    webSocket.value.onerror = (error: any) => {
      console.log(error, 'error')
      console.error('WebSocket 发生错误: ', error)
      src.value = `${publicPath}/image/error.png`
    }
  }
  else {
    src.value = `${publicPath}/image/normal.png`
  }
})
onUnmounted(() => {
  if (webSocket.value) {
    webSocket.value.close()
    webSocket.value = ''
    src.value = `${publicPath}/image/normal.png`
  }
})
</script>

<template>
  <img :src="src" style="width: 100%; height: 100%; background-color: rgb(0 0 0 / 70%);" alt="视频流" object-fit="cover">
  <!-- <el-image style="width: 100%; height: 100%; background-color: rgb(0 0 0 / 70%);" :src="src" fit="fill" /> -->
</template>