[Python] How to create simple webrtc server to browser stream example in python?

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to write simple python server to browser video streamer using aiortc? For simplicity the server and the browser are in one local network.

    The python code:

    import asyncio
    from aiortc import RTCPeerConnection, RTCSessionDescription, VideoStreamTrack
    from av import VideoFrame
    import numpy as np
    import uuid
    import cv2
    from aiohttp import web

    class BouncingBallTrack(VideoStreamTrack):

    def __init__(self):
    super().__init__()
    self.width = 640
    self.height = 480
    [...]

    async def recv(self):
    [...]
    return new_frame


    async def offer(request):
    params = await request.json()
    offer = RTCSessionDescription(sdp=params["sdp"], type=params["type"])

    pc = RTCPeerConnection()

    # Add local media track
    pc.addTrack(BouncingBallTrack())

    await pc.setRemoteDescription(offer)
    answer = await pc.createAnswer()
    await pc.setLocalDescription(answer)

    return {
    "sdp": pc.localDescription.sdp,
    "type": pc.localDescription.type
    }

    if __name__ == "__main__":

    app = web.Application()

    app.router.add_post("/offer", offer)
    app.router.add_static('/', path='static', name='static')

    web.run_app(app, port=8080)


    The JavaScript code:

    pc = new RTCPeerConnection({
    iceServers: [] // No ICE servers needed for local network
    });

    // When remote adds a track, show it in our video element
    pc.ontrack = event => {
    if (event.track.kind === 'video') {
    video.srcObject = event.streams[0];
    }
    };

    // Create an offer to send to the server
    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);

    // Send the offer to the server and get the answer
    const response = await fetch('/offer', {
    method: 'POST',
    headers: {
    'Content-Type': 'application/json'
    },
    body: JSON.stringify({
    sdp: pc.localDescription.sdp,
    type: pc.localDescription.type
    })
    });

    const answer = await response.json();
    await pc.setRemoteDescription(new RTCSessionDescription(answer));



    When a client sends the offer, the server failes with ValueError: None is not in list on line await pc.setLocalDescription(answer). Actually sdp in the offer and in the answer are so strange that it cannot work. The browser and the server sdp do not contain any information about stream tracks, neither contains any local network address to connect. What I'm missing?

    Continue reading...

Compartilhe esta Página