WebRtcStreamer 是一个基于 WebRTC 协议的轻量级开源工具,可以在浏览器中直接播放 RTSP 视频流。它利用 WebRTC 的强大功能,提供低延迟的视频流播放体验,非常适合实时监控和其他视频流应用场景。
本文将介绍如何在Vue.js
项目中使用 WebRtcStreamer
实现实时视频流播放,并分享相关的代码示例。
注意
:只支持H264
格式
流媒体方式文章
使用 Vue 和 flv.js 实现流媒体视频播放:完整教程
VUE项目中优雅使用EasyPlayer实时播放摄像头多种格式视频使用版本信息为5.xxxx
实现步骤
-
安装和配置 WebRtcStreamer 服务端
要使用 WebRtcStreamer,需要先在服务器上部署其服务端。以下是基本的安装步骤: -
从 WebRtcStreamer 官方仓库 下载代码。
启动命令
或者双击exe程序
服务启动后,默认会监听8000
端口,访问 http://<server_ip>:8000 可查看状态。
更改默认端口命令:webrtc-streamer.exe -o -H 0.0.0.0:9527
2.集成到vue中
webRtcStreamer.js
不需要在html文件中引入webRtcStreamer相关代码
/**
* @constructor
* @param {string} videoElement - dom ID
* @param {string} srvurl - WebRTC 流媒体服务器的 URL(默认为当前页面地址)
*/
class WebRtcStreamer {
constructor(videoElement, srvurl) {
if (typeof videoElement === 'string') {
this.videoElement = document.getElementById(videoElement);
} else {
this.videoElement = videoElement;
}
this.srvurl =
srvurl || `${
location.protocol}//${
window.location.hostname}:${
window.location.port}`;
this.pc = null; // PeerConnection 实例
// 媒体约束条件
this.mediaConstraints = {
offerToReceiveAudio: true,
offerToReceiveVideo: true,
};
this.iceServers = null; // ICE 服务器配置
this.earlyCandidates = []; // 提前收集的候选者
}
/**
* HTTP 错误处理器
* @param {Response} response - HTTP 响应
* @throws {Error} 当响应不成功时抛出错误
*/
_handleHttpErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
/**
* 连接 WebRTC 视频流到指定的 videoElement
* @param {string} videourl - 视频流 URL
* @param {string} audiourl - 音频流 URL
* @param {string} options - WebRTC 通话的选项
* @param {MediaStream} localstream - 本地流
* @param {string} prefmime - 优先的 MIME 类型
*/
connect(videourl, audiourl, options, localstream, prefmime) {
this.disconnect();
if (!this.iceServers) {
console.log('获取 ICE 服务器配置...');
fetch(`${
this.srvurl}/api/getIceServers`)
.then(this._handleHttpErrors)
.then((response) => response.json())
.then((response) =>
this.onReceiveGetIceServers(response, videourl, audiourl, options, localstream, prefmime),
)
.catch((error) => this.onError(`获取 ICE 服务器错误: ${
error}`));
} else {
this.onReceiveGetIceServers(
this.iceServers,
videourl,
audiourl,
options,
localstream,
prefmime,
);
}
}
/**
* 断开 WebRTC 视频流,并清空 videoElement 的视频源
*/
disconnect() {
if (this.videoElement?.srcObject) {
this.videoElement.srcObject.getTracks().forEach((track) => {
track.stop();
this.videoElement.<