主流视频流格式及 Vue3 实现方案

发布于:2025-07-03 ⋅ 阅读:(18) ⋅ 点赞:(0)
1. HLS (HTTP Live Streaming)
  • 技术原理:基于 HTTP 的流媒体协议,使用 .m3u8 索引文件 + .ts 分片文件。

  • 特点:高兼容性(尤其 iOS)、10+秒延迟、支持自适应码率。

  • Vue3 实现(video.js)

npm install video.js videojs-contrib-hls
<template>
  <div>
    <video ref="videoPlayer" class="video-js vjs-default-skin"></video>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';
import 'videojs-contrib-hls';

const videoPlayer = ref(null);
const player = ref(null);
const videoUrl = 'http://example.com/stream.m3u8';

onMounted(() => {
  player.value = videojs(videoPlayer.value, {
    sources: [{ src: videoUrl, type: 'application/x-mpegURL' }],
    autoplay: true,
    controls: true
  });
});

onUnmounted(() => {
  if (player.value) player.value.dispose();
});
</script>

2. FLV (HTTP-FLV)
  • 技术原理:基于 HTTP 长连接的流媒体,延迟 1-3 秒,适合直播。

  • Vue3 实现(flv.js)

npm install flv.js
<template>
  <video ref="videoEl" muted autoplay controls></video>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import flvjs from 'flv.js';

const videoEl = ref(null);
const flvPlayer = ref(null);
const videoUrl = 'http://example.com/stream.flv';

onMounted(() => {
  if (flvjs.isSupported()) {
    flvPlayer.value = flvjs.createPlayer({
      type: 'flv',
      url: videoUrl,
      isLive: true // 直播流
    });
    flvPlayer.value.attachMediaElement(videoEl.value);
    flvPlayer.value.load();
    flvPlayer.value.play();
  }
});

onUnmounted(() => {
  flvPlayer.value?.destroy();
});
</script>
3. RTSP (Real Time Streaming Protocol)
  • 技术痛点:浏览器原生不支持,需转码或插件。

  • 方案一:转 HLS/FLV
    通过 FFmpeg 服务器转码(延迟增加 2-5 秒)。

  • 方案二:Web 插件播放(低延迟)
    EasyPlayer.js 示例

npm install @easydarwin/easyplayer
<template>
  <EasyPlayer :videoUrl="rtspUrl" live autoplay />
</template>

<script setup>
import EasyPlayer from '@easydarwin/easyplayer';
const rtspUrl = 'rtsp://example.com/stream';
</script>

✅ 支持 H.265,延迟 <1秒,但需部署 WASM 文件。

4. WebRTC (超低延迟方案)
  • 技术原理:点对点传输,延迟 <500ms,适合实时互动。

  • Vue3 实现(示例框架)

<template>
  <video ref="videoEl" autoplay></video>
</template>

<script setup>
import { ref, onMounted } from 'vue';
const videoEl = ref(null);

onMounted(async () => {
  const stream = await navigator.mediaDevices.getUserMedia({ video: true });
  videoEl.value.srcObject = stream;
});
</script>

⚙️ 二、关键优化与兼容性策略

  1. 多格式回退:优先 FLV/HLS,RTSP 转码兜底。

  2. 延迟优化

    • 调小 HLS 分片时长(需服务器配合)

    • FLV 启用低延迟模式(stashInitialSize: 128

  3. 响应式设计

    video { max-width: 100%; height: auto; }
  4. 错误处理:监听 error 事件切换备用源。

💡 生产环境建议

  • 优先使用 FLV 方案(flv.js)平衡延迟与兼容性;

  • 旧系统监控考虑 EasyPlayer.js 支持 H.2653;

  • 避免直接使用 RTMP(依赖 Flash,已淘汰)。


网站公告

今日签到

点亮在社区的每一天
去签到