Skip to content

🤖 Assistant

以下是使用 mediamtx 时前端的完整实现方案(根据延迟要求/设备兼容性选择不同技术),提供可直接落地的代码:


🌐 前端三大播放方案 (附代码模板)

⚡ 方案一:WebRTC播放 (超低延迟 200-500ms)

html
<!DOCTYPE html>
<video id="webrtc-video" autoplay muted controls width="800"></video>

<script>
// 核心播放函数
async function playVideo(streamName) {
  const pc = new RTCPeerConnection({
    iceServers: [{ urls: "stun:stun.l.google.com:19302" }] // NAT穿透
  });

  // 视频流接收处理
  pc.ontrack = (event) => {
    if (event.track.kind === 'video') {
      document.getElementById('webrtc-video').srcObject = event.streams[0];
    }
  };

  // 创建Offer并发送给mediamtx
  const offer = await pc.createOffer();
  await pc.setLocalDescription(offer);
  
  const response = await fetch(
    `http://你的服务器IP:8889/${streamName}/whep`, // 注意替换IP
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/sdp' },
      body: offer.sdp
    }
  );
  
  // 设置远端SDP
  const answer = await response.json();
  await pc.setRemoteDescription(answer);
}

// 启动播放 (传入mediamtx中配置的流名称)
playVideo('front_door').catch(console.error);
</script>

📡 方案二:HTTP-FLV播放 (延迟1-3s)

html
<script src="https://cdn.jsdelivr.net/npm/flv.js@1.6.2/dist/flv.min.js"></script>

<video id="flv-video" controls width="800"></video>

<script>
const streamName = 'front_door'; // 对应mediamtx配置的路径名

// 初始化FLV播放器
if (flvjs.isSupported()) {
  const videoElement = document.getElementById('flv-video');
  const flvPlayer = flvjs.createPlayer({
    type: 'flv',
    url: `http://你的服务器IP:8888/${streamName}`, // HTTP-FLV地址
  });
  flvPlayer.attachMediaElement(videoElement);
  flvPlayer.load();
  flvPlayer.play(); // 自动播放需页面先交互
} else {
  alert('您的浏览器不支持FLV播放');
}
</script>

📼 方案三:HLS播放 (延迟约10s,兼容iOS最佳)

html
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.10/dist/hls.min.js"></script>

<video id="hls-video" controls width="800"></video>

<script>
const streamName = 'front_door';
const video = document.getElementById('hls-video');

if (Hls.isSupported()) {
  const hls = new Hls();
  hls.loadSource(`http://你的服务器IP:8888/${streamName}/hls.m3u8`);
  hls.attachMedia(video);
  hls.on(Hls.Events.MANIFEST_PARSED, () => video.play());
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
  // iOS原生支持
  video.src = `http://你的服务器IP:8888/${streamName}/hls.m3u8`;
}
</script>

🔧 关键配置说明 (mediamtx端)

mediamtx.yml 中确保开启以下服务:

yaml
httpEnabled: true       # 启用HTTP服务 (用于HLS/FLV)
httpPort: 8888          # 前端访问端口

webrtcEnabled: true     # 启用WebRTC
webrtcAllowOrigin: "*"  # 允许跨域

paths:
  front_door:           # 与前端streamName对应
    source: rtsp://admin:123456@192.168.1.101 # 实际摄像头地址
    sourceProtocol: tcp

🛠️ 调试技巧 (前端开发者必看)

  1. 获取播放URL

    • WebRTC: http://服务器IP:8889/<流名>/whep (POST)
    • FLV: http://服务器IP:8888/<流名>
    • HLS: http://服务器IP:8888/<流名>/hls.m3u8
  2. 跨域处理

    yaml
    # mediamtx.yml 添加
    httpAllowOrigin: "*"
  3. HTTPS强制环境 (如Safari):

    html
    <!-- 本地测试可用nginx反代 -->
    <script>
      if (window.location.protocol === 'https:') {
        mediamtxUrl = mediamtxUrl.replace('http:', 'https:'); // 自动协议切换
      }
    </script>

📱 多设备兼容方案

设备类型推荐协议核心代码
PC浏览器WebRTCnew RTCPeerConnection()
安卓/ChromeHTTP-FLVflvjs.createPlayer()
iOS/SafariHLSvideo.src = '*.m3u8'
微信内置浏览器优先HLS检测UA使用不同加载逻辑

实时设备检测代码示例:

javascript
function initPlayer() {
  const ua = navigator.userAgent;
  const isIOS = /iPhone|iPad|iPod/i.test(ua);
  
  if (isIOS) {
    initHLSPlayer(); // 调用HLS方案
  } else if (typeof RTCPeerConnection !== 'undefined') {
    initWebRTC();    // WebRTC方案
  } else {
    initFLVPlayer(); // 降级到FLV
  }
}

⚠️ 生产环境必做

  1. WebRTC需HTTPS环境,可用Let's Encrypt免费证书
  2. 大并发场景用Nginx做mediamtx负载均衡
  3. 摄像头验证失败时添加 sourceOnDemand: yes 配置

完整前端示例项目: mediamtx-web-demo

本站总访问量 次 本站访客数 人次

1111111111111111111