You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中如何播放RTSP流视频?已尝试多库未解决

在React项目中播放RTSP流的解决方案

浏览器原生不支持RTSP协议,这是你用React Player、VideoJs直接播放失败的核心原因。以下是几种可行的实现方案:

方案1:将RTSP转成浏览器支持的HLS/HTTP-FLV流

这是目前最通用的方案,通过流媒体服务器或FFmpeg将RTSP流转码为HLS(HTTP Live Streaming)或HTTP-FLV格式,再用前端库播放。

步骤:

  1. 转流处理

    • 本地测试用FFmpeg转流:
      ffmpeg -i rtsp://your-rtsp-url -c:v libx264 -c:a aac -f hls -hls_time 2 -hls_list_size 5 -hls_flags delete_segments ./hls/stream.m3u8
      
    • 生产环境推荐用SRS、EasyDarwin等流媒体服务器做稳定转流,配置后可直接获取HLS/FLV的播放地址。
  2. React中播放转后的流
    以VideoJs + hls.js为例:

    import React, { useEffect, useRef } from 'react';
    import videojs from 'video.js';
    import 'video.js/dist/video-js.css';
    import Hls from 'hls.js';
    
    const RtspPlayer = ({ streamUrl }) => {
      const videoRef = useRef(null);
      let player = null;
    
      useEffect(() => {
        if (!videoRef.current) return;
    
        player = videojs(videoRef.current, {
          controls: true,
          autoplay: false,
          preload: 'auto',
        });
    
        if (Hls.isSupported()) {
          const hls = new Hls();
          hls.loadSource(streamUrl);
          hls.attachMedia(videoRef.current);
        } else if (videoRef.current.canPlayType('application/vnd.apple.mpegurl')) {
          videoRef.current.src = streamUrl;
        }
    
        return () => {
          if (player) player.dispose();
        };
      }, [streamUrl]);
    
      return (
        <div data-vjs-player>
          <video ref={videoRef} className="video-js vjs-big-play-centered" />
        </div>
      );
    };
    
    export default RtspPlayer;
    

    使用时传入转后的HLS地址:<RtspPlayer streamUrl="http://your-server/hls/stream.m3u8" />

方案2:基于WebRTC直接拉取RTSP流

WebRTC支持低延迟的实时流传输,可通过中间服务将RTSP转成WebRTC流后在React中播放。

示例(使用react-webrtc-rtsp组件):

import React from 'react';
import RtspWebRtc from 'react-webrtc-rtsp';

const RtspWebRtcPlayer = ({ rtspUrl }) => {
  return (
    <RtspWebRtc
      url={rtspUrl}
      width="100%"
      height="auto"
      controls={true}
    />
  );
};

export default RtspWebRtcPlayer;

注意:这类组件依赖后端的WebRTC转流服务,需要确保后端已配置好RTSP到WebRTC的转换逻辑。

方案3:使用浏览器插件(不推荐)

旧版IE或部分浏览器支持ActiveX插件(如VLC插件)来播放RTSP,但现代浏览器已逐步淘汰这类插件,兼容性极差,不建议在生产环境使用。


内容的提问来源于stack exchange,提问作者JiangCheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:42:41