vue3 实时播放视频
时间: 2025-07-13 11:55:33 浏览: 4
在 Vue 3 中实现实时视频播放功能,可以通过多种技术方案实现,尤其适用于处理 RTSP 流媒体协议的场景。以下是一个基于 `webrtc-streamer` 和 Vue 3 的实现思路,并结合 TypeScript、Vite 等现代前端技术栈进行开发[^3]。
### 使用 `webrtc-streamer` 实现 RTSP 视频流播放
`webrtc-streamer` 是一个轻量级库,支持通过 WebRTC 技术将 RTSP 流转换为网页端可播放的视频流,适用于监控摄像头等设备的实时视频传输。
#### 安装依赖
使用 Vite 创建项目后,可以安装 `webrtc-streamer`:
```bash
npm install webrtc-streamer
```
#### 在 Vue 组件中使用
以下是一个基于 Vue 3 + TypeScript 的组件示例,展示如何加载和播放 RTSP 视频流:
```vue
<template>
<div class="video-container">
<video ref="videoRef" autoplay playsinline></video>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import WebRTCStreamer from 'webrtc-streamer'
const videoRef = ref<HTMLVideoElement | null>(null)
let streamer: WebRTCStreamer | null = null
onMounted(() => {
if (videoRef.value) {
streamer = new WebRTCStreamer({
videoElement: videoRef.value,
url: 'rtsp://your-rtsp-stream-url', // 替换为实际的 RTSP 地址
})
streamer.connect()
}
})
</script>
<style scoped>
.video-container {
width: 100%;
max-width: 800px;
margin: auto;
}
video {
width: 100%;
height: auto;
}
</style>
```
### 使用 Element Plus 实现弹框与拖拽功能
为了实现可拖动的弹窗,可以结合 Element Plus 的 `el-dialog` 组件,并通过自定义指令或 CSS 实现拖拽行为。
#### 示例:带拖拽功能的弹窗组件
```vue
<template>
<el-dialog v-model="visible" title="实时视频" :show-close="false" :modal="false" :custom-style="{ width: '600px' }" draggable>
<video ref="videoRef" autoplay playsinline style="width: 100%;"></video>
</el-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import WebRTCStreamer from 'webrtc-streamer'
const visible = ref(true)
const videoRef = ref<HTMLVideoElement | null>(null)
let streamer: WebRTCStreamer | null = null
onMounted(() => {
if (videoRef.value) {
streamer = new WebRTCStreamer({
videoElement: videoRef.value,
url: 'rtsp://your-rtsp-stream-url',
})
streamer.connect()
}
})
</script>
```
### 注意事项
- **跨域问题**:确保 RTSP 流地址可通过代理访问,避免浏览器因 CORS 限制无法加载。
- **性能优化**:对于多路视频流,需合理控制资源占用,防止页面卡顿。
- **兼容性**:WebRTC 支持主流浏览器,但某些旧版本可能不兼容,建议提供备用方案如 HLS 播放。
---
阅读全文
相关推荐


















