You need to enable JavaScript to run this app. 如何在网页端展示并播放每秒更新的直播二进制流数据
优惠活动
大模型
产品
解决方案
定价
更多

如何在网页端展示并播放每秒更新的直播二进制流数据

实现方案

1. 优化后端抓取转发服务

你当前的Python代码仅将直播二进制流追加写入本地文件,无法支撑实时直播播放的需求,首先需要改造为兼具流抓取、实时转发能力的后端服务:

  • 首先修复原代码的IO性能问题:原代码每次收到视频帧都重复打开关闭文件,效率极低,建议取消实时写本地文件的逻辑,改为用内存队列暂存最近的流分片,需要落地存储的话单独开异步线程处理
  • 新增HTTP服务能力:可以用FastAPI/Flask等轻量框架实现,对外暴露直播流接口,支持跨域访问(适配你自己的网站域名)
  • 流转发逻辑:你抓取到的是**碎片化MP4(fMP4)**格式的分片,每一段二进制都是可独立解码的分片,无需额外编码,直接转发给前端即可
    核心改造代码示例:
# 先安装依赖:pip install fastapi uvicorn websocket-client
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
import asyncio
import threading
from collections import deque
import websocket
import json

app = FastAPI()
# 生产环境把*替换成你自己的网站域名,避免跨域问题
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置队列最大长度,控制内存占用,比如存最近30秒的流分片
stream_queue = deque(maxlen=100)
stream_running = False
# 全局存储fMP4头信息,首次收到流的时候提取,每次新用户请求先发送头
mp4_header = b""

def on_message(ws, message):
    global mp4_header
    try:
        json.loads(message)
        print(f"收到控制信令:{message}")
    except ValueError:
        # 首次收到的流里包含fMP4的ftyp+moov头,存下来复用
        if not mp4_header and b"ftyp" in message:
            mp4_header = message[:message.index(b"moof")] if b"moof" in message else message
        stream_queue.append(message)

def on_error(ws, error):
    print(f"连接错误:{error}")

def on_close(ws, d, c):
    global stream_running
    stream_running = False
    print("WebSocket连接关闭")

def on_open(ws):
    def run():
        while stream_running:
            ws.send("Hello")
            # 注意不要死循环无间隔发,会被源站封
            asyncio.sleep(1)
    threading.Thread(target=run, daemon=True).start()

def connect_ws():
    global stream_running
    stream_running = True
    ws_url = "wss://bintu-h5live-secure.nanocosmos.de/h5live/authstream/stream.mp4/?url=rtmp%3A%2F%2Fbintu-splay.nanocosmos.de%3A1935%2Fsplay&stream=Av7gf-8VFKd&cid=788213&pid=15225378643&token=498926e198c330ffcb8e25e7470fe1a6%2Beea9c39334dca9b5aa2d7d31ed28abf2&expires=1622528020&options=13&tag=teen20"
    ws = websocket.WebSocketApp(
        ws_url,
        on_open=on_open,
        on_message=on_message,
        on_error=on_error,
        on_close=on_close
    )
    ws.run_forever(origin="https://beeta777.com")

# 对外暴露的直播流接口
@app.get("/live/stream")
async def get_stream():
    async def stream_generator():
        # 先发送MP4头,保证播放器能正常识别格式
        if mp4_header:
            yield mp4_header
        while stream_running:
            if stream_queue:
                yield stream_queue.popleft()
            else:
                await asyncio.sleep(0.01)
    return Response(stream_generator(), media_type="video/mp4")

if __name__ == "__main__":
    # 单独开线程跑WebSocket抓取逻辑
    threading.Thread(target=connect_ws, daemon=True).start()
    # 启动HTTP服务,端口可自行修改
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

2. 前端页面播放实现

你自己的网站页面直接用HTML5 video标签配合成熟的播放器组件即可实现播放,不需要复杂的逻辑:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>直播播放</title>
    <!-- 生产环境请将播放器资源下载到你自己的服务器本地引用 -->
    <link rel="stylesheet" href="./video-js.min.css">
</head>
<body>
    <video
        id="live-player"
        class="video-js vjs-big-play-centered"
        controls
        preload="auto"
        width="1280"
        height="720"
    >
        <!-- 这里的IP改成你部署Python服务的服务器公网IP或者域名 -->
        <source src="http://你的服务IP:8000/live/stream" type="video/mp4">
    </video>
    <!-- 生产环境请将播放器资源下载到你自己的服务器本地引用 -->
    <script src="./video-js.min.js"></script>
    <script>
        const player = videojs('live-player', {
            autoplay: true,
            liveui: true,
            fluid: true
        });
    </script>
</body>
</html>

3. 注意事项

  • 你当前用的WebSocket链接里的token有过期时间,你需要自己实现token的自动刷新逻辑,过期后重新获取有效链接重连,避免直播中断
  • 多用户访问的场景下,后端仅需要抓取一次源站流,分发给所有前端请求即可,不要每个用户都单独抓取一次源站,避免带宽浪费和被源站封禁
  • 如果需要更低的播放延迟,可以改为后端通过WebSocket直接推流给前端,前端用MediaSource Extensions API将流喂给video标签,延迟可以降到1秒以内
  • 不要直接将源站的WebSocket/播放链接放到前端使用,源站做了origin校验,你的网站域名不在白名单内会被拦截,必须走自己的后端服务做转发

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 13:54:04