vue实现实时视频
使用 Vue 实现实时视频流
在 Vue 中实现实时视频流通常涉及浏览器 API(如 getUserMedia)和视频播放组件。以下是实现方法:
获取摄像头权限并显示视频流
通过 navigator.mediaDevices.getUserMedia 获取摄像头权限,并将视频流绑定到 <video> 元素。
<template>
<div>
<video ref="videoElement" autoplay playsinline></video>
<button @click="startVideo">开启摄像头</button>
<button @click="stopVideo">关闭摄像头</button>
</div>
</template>
<script>
export default {
data() {
return {
stream: null
};
},
methods: {
async startVideo() {
try {
this.stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: false
});
this.$refs.videoElement.srcObject = this.stream;
} catch (err) {
console.error("无法访问摄像头:", err);
}
},
stopVideo() {
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop());
this.$refs.videoElement.srcObject = null;
}
}
},
beforeDestroy() {
this.stopVideo();
}
};
</script>
使用第三方库实现更复杂功能
如果需要更高级的功能(如录制、滤镜),可以使用以下库:
- RecordRTC:实现视频录制和截图。
- Vue-Video-Player:基于 Video.js 的 Vue 视频播放组件。
npm install recordrtc vue-video-player
实现视频录制
结合 RecordRTC 录制视频流:
<template>
<div>
<video ref="videoElement" autoplay playsinline></video>
<button @click="startRecording">开始录制</button>
<button @click="stopRecording">停止录制</button>
</div>
</template>
<script>
import RecordRTC from "recordrtc";
export default {
data() {
return {
recorder: null,
stream: null
};
},
methods: {
async startRecording() {
this.stream = await navigator.mediaDevices.getUserMedia({
video: true,
audio: true
});
this.$refs.videoElement.srcObject = this.stream;
this.recorder = new RecordRTC(this.stream, { type: "video" });
this.recorder.startRecording();
},
async stopRecording() {
if (this.recorder) {
this.recorder.stopRecording(() => {
const blob = this.recorder.getBlob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "recorded-video.webm";
a.click();
});
}
if (this.stream) {
this.stream.getTracks().forEach(track => track.stop());
}
}
}
};
</script>
实现视频滤镜
通过 Canvas 和 CSS 滤镜实现视频特效:
<template>
<div>
<video ref="videoElement" autoplay playsinline></video>
<canvas ref="canvasElement"></canvas>
<button @click="applyFilter('grayscale')">黑白滤镜</button>
</div>
</template>
<script>
export default {
methods: {
applyFilter(filter) {
const video = this.$refs.videoElement;
const canvas = this.$refs.canvasElement;
const ctx = canvas.getContext("2d");
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
ctx.filter = filter === "grayscale" ? "grayscale(100%)" : "none";
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
}
}
};
</script>
注意事项
- HTTPS 环境:
getUserMedia在大多数浏览器中仅支持 HTTPS 或 localhost。 - 权限提示:用户需明确授权摄像头和麦克风访问权限。
- 移动端适配:添加
playsinline属性以确保视频在移动端内联播放。
以上方法涵盖了从基础视频流到高级功能(录制、滤镜)的实现。根据需求选择合适的方案即可。







