WebRTC(TODO)

1 简介

只是简单学学。。。

简单看了下,貌似就是SIP的下一代。因为我对SIP很熟,所以就比对着来写。

传统的SIP

WebRTC

网络端

终端

2 树莓派的实现

代码

bash 复制代码
webrtc-pi/
├── server.py
├── static/
│   └── client.html

server.py

python 复制代码
import cv2
import asyncio
from aiortc import MediaStreamTrack, RTCPeerConnection, RTCSessionDescription
from aiortc.contrib.media import MediaRelay
from flask import Flask, render_template, request, jsonify, send_from_directory
import json

app = Flask(__name__, static_url_path='')

pcs = set()
relay = MediaRelay()

# 视频采集轨道(OpenCV)
class VideoTrack(MediaStreamTrack):
    kind = "video"

    def __init__(self):
        super().__init__()
        self.cap = cv2.VideoCapture(0)

    async def recv(self):
        pts, time_base = await self.next_timestamp()
        ret, frame = self.cap.read()
        if not ret:
            return None
        # 关键:OpenCV 转 RGB
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        from av import VideoFrame
        video_frame = VideoFrame.from_ndarray(frame, format="rgb24")
        video_frame.pts = pts
        video_frame.time_base = time_base
        return video_frame

@app.route('/')
def index():
    return send_from_directory('static', 'client.html')

@app.route('/offer', methods=['POST'])
def offer():
    offer_sdp = request.get_json()
    pc = RTCPeerConnection()
    pcs.add(pc)

    video = VideoTrack()
    pc.addTrack(video)

    async def create_answer():
        await pc.setRemoteDescription(RTCSessionDescription(**offer_sdp))
        answer = await pc.createAnswer()
        await pc.setLocalDescription(answer)
        return pc.localDescription

    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    desc = loop.run_until_complete(create_answer())
    return jsonify({'sdp': desc.sdp, 'type': desc.type})

@app.route('/answer', methods=['POST'])
def answer():
    return "OK"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

client.html

html 复制代码
<!DOCTYPE html>
<html>
<head>
  <title>Raspberry Pi WebRTC Camera</title>
</head>
<body>
  <h2>WebRTC Camera Stream</h2>
  <video id="video" autoplay playsinline controls></video>
  <script>
    const pc = new RTCPeerConnection();
    const video = document.getElementById("video");

    pc.ontrack = function (event) {
      video.srcObject = event.streams[0];
    };

    fetch("/offer", { method: "POST" })
      .then(res => res.json())
      .then(async ({ sdp, type }) => {
        await pc.setRemoteDescription({ sdp, type });
        const answer = await pc.createAnswer();
        await pc.setLocalDescription(answer);

        fetch("/answer", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(pc.localDescription),
        });
      });
  </script>
</body>
</html>

TODO

相关推荐
diygwcom8 小时前
个人理解 火山引擎的实时对话 AI 如何利用 WebRTC、大模型、语音识别(ASR)、语音合成(TTS)等技术实现低延迟的实时对话功能。
人工智能·webrtc·火山引擎
谷云龙GGBond1 天前
【WebRTC】源码更改麦克风权限
webrtc
achene_ql2 天前
基于 WebRTC 的一对一屏幕共享项目(一)——项目简介
javascript·websocket·node.js·webrtc·html5
易风有点疯3 天前
浏览器播放 WebRTC 视频流
webrtc
今天也想MK代码5 天前
基于WebRTC的实时语音对话系统:从语音识别到AI回复
人工智能·webrtc·语音识别
红米饭配南瓜汤8 天前
WebRTC中的几个Channel
网络协议·音视频·webrtc·媒体
腾讯云音视频8 天前
AI实时对话的通信基础,WebRTC技术综合指南
人工智能·webrtc
achene_ql12 天前
WebRTC:去中心化网络P2P框架解析
网络·去中心化·webrtc·p2p
唯独失去了从容12 天前
WebRTC通信原理与流程
webrtc
拧螺丝专业户13 天前
外网访问内网海康威视监控视频的方案:WebRTC + Coturn 搭建
音视频·webrtc·监控视频