Skip to main content

Baidu Real-Time Communication (BRTC) Python SDK

Project description

BRTC Python SDK

Python Version License

Baidu Real-Time Communication (BRTC) Python SDK - 基于 aiortc 和信令的实时音视频通信 SDK。

特性

  • 完整的 WebRTC 支持: 基于 aiortc 实现,支持音视频通信、数据通道
  • 多种音视频发送方式: 支持 aiortc 采集和直接发送编码后数据
  • 完整的VideoRoom 支持: 房间管理、用户管理、发布/订阅
  • 数据通道: 支持文本和二进制数据发送/接收
  • 异步设计: 基于 asyncio,高性能非阻塞

安装

pip install baidurtc

快速开始

基础使用示例

import asyncio
from baidurtc import BaiduRtcClient, EventObserver

class MyEventObserver(EventObserver):
    def on_rtc_login_ok(self):
        print("登录成功")
    
    def on_rtc_webrtc_up(self, feed_id: int):
        print(f"WebRTC 连接建立: feed_id={feed_id}")
    
    def on_rtc_feed_coming(self, feed_id: int, name: str):
        print(f"用户加入: {name} (feed_id={feed_id})")
    
    def on_rtc_user_message(self, feed_id: int, msg: str):
        print(f"收到消息 from {feed_id}: {msg}")

async def main():
    # 创建客户端并配置 (Fluent API)
    client = (
        BaiduRtcClient()
        .set_app_id("your-app-id")
        .set_room_name("test-room")
        .set_user_id(12345)
        .set_display_name("User123")
        .set_token("your-token")
        .set_server_url("wss://rtc.exp.bcelive.com/janus")
        .set_audio_codec("opus")
        .set_video_codec("H264")
        .set_has_audio(True)
        .set_has_video(True)
        .set_has_data(True)
    )
    
    # 设置事件观察者
    client.set_event_observer(MyEventObserver())
    
    # 登录并加入房间
    await client.login()
    
    # 等待一段时间
    await asyncio.sleep(60)
    
    # 退出
    await client.logout()

if __name__ == "__main__":
    asyncio.run(main())

音视频发送示例

import asyncio
from baidurtc import BaiduRtcClient

async def send_media():
    client = (
        BaiduRtcClient()
        .set_app_id("your-app-id")
        .set_room_name("test-room")
        .set_user_id(12345)
        .set_display_name("User123")
        .set_token("your-token")
        .set_has_audio(True)
        .set_has_video(True)
    )
    
    await client.login()
    
    # 方式1: 使用 aiortc 自动采集
    audio_devices = await client.media.sources.enumerate_audio_devices()
    video_devices = await client.media.sources.enumerate_video_devices()
    
    await client.media.sources.start_microphone(device_id=audio_devices[0].device_id)
    await client.media.sources.start_camera(device_id=video_devices[0].device_id)
    await client.media.sources.start_sending()
    
    # 方式2: 直接发送编码后的数据
    # 发送 H264 视频帧
    # await client.send_video(h264_frame_data, duration_ms=33)
    
    # 发送 Opus 音频帧
    # await client.send_audio(opus_frame_data, duration_ms=20)
    
    # 发送 PCM 音频 (自动编码)
    # await client.send_audio_pcm(pcm_data, duration_ms=20)
    
    await asyncio.sleep(60)
    await client.logout()

asyncio.run(send_media())

数据通道使用示例

import asyncio
from baidurtc import BaiduRtcClient

async def data_channel_demo():
    client = BaiduRtcClient()
    # ... 配置和登录 ...
    
    # 注册数据接收回调
    def on_data_received(data, label):
        print(f"收到数据 [{label}]: {data}")
    
    client.data_channel.on_data(on_data_received)
    
    # 发送数据
    await client.send_data("Hello, World!")
    await client.send_raw_data(b"Binary data")
    
    # 或通过数据通道管理器发送
    await client.data_channel.send_json({"action": "ping"})
    await client.data_channel.send_message("用户消息", to_user=0)

asyncio.run(data_channel_demo())

架构

┌─────────────────────────────────────────────────────────────┐
│                    BaiduRtcClient                           │
├─────────────────────────────────────────────────────────────┤
│  RoomManager │ UserManager │ MediaManager │ DataChannelMgr  │
├─────────────────────────────────────────────────────────────┤
│            MediaSourceManager │ SignalingManager            │
├─────────────────────────────────────────────────────────────┤
│              WebSocketClient │ BRTCProtocol                 │
├─────────────────────────────────────────────────────────────┤
│                    aiortc (WebRTC)                          │
├─────────────────────────────────────────────────────────────┤
│                           BRTC                              │
└─────────────────────────────────────────────────────────────┘

API 文档

主客户端类

  • login() - 登录到 BRTC 服务器
  • logout() - 退出登录
  • send_video(frame, duration_ms) - 发送视频帧
  • send_audio(frame, duration_ms) - 发送音频帧
  • send_audio_pcm(pcm_data, duration_ms) - 发送 PCM 音频
  • send_data(text) - 发送数据通道文本
  • send_raw_data(bytes) - 发送数据通道二进制数据

配置方法 (Fluent API)

  • set_app_id(app_id) - 设置应用 ID
  • set_room_name(room_name) - 设置房间名称
  • set_user_id(user_id) - 设置用户 ID
  • set_display_name(name) - 设置显示名称
  • set_token(token) - 设置认证 Token
  • set_audio_codec(codec) - 设置音频编解码器
  • set_video_codec(codec) - 设置视频编解码器
  • set_has_audio(enabled) - 启用/禁用音频
  • set_has_video(enabled) - 启用/禁用视频
  • set_has_data(enabled) - 启用/禁用数据通道

观察者接口

  • EventObserver - 事件观察者

    • on_rtc_login_ok() - 登录成功
    • on_rtc_webrtc_up(feed_id) - WebRTC 连接建立
    • on_rtc_feed_coming(feed_id, name) - 用户加入
    • on_rtc_user_message(feed_id, msg) - 收到消息
    • ...
  • MediaObserver - 媒体观察者

    • on_video_frame(feed_id, data, codec) - 收到视频帧
    • on_audio_data(feed_id, data, sample_rate, channels) - 收到音频数据
    • ...

更多示例

查看 sdkdemo/ 目录获取更多使用示例:

  • basic_usage.py - 基础使用
  • media_sending.py - 音视频发送
  • data_channel.py - 数据通道
  • push_demo.py - 推流演示(从本地文件推送音视频)
  • pull_demo.py - 拉流演示(订阅远端流)
  • videocall_demo.py - 视频通话演示

依赖

  • Python 3.8+
  • aiortc >= 1.6.0
  • websockets >= 11.0
  • av >= 10.0.0

协议

BSD-3-Clause License

相关链接

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

baidurtc-0.0.1.tar.gz (38.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

baidurtc-0.0.1-py3-none-any.whl (36.3 kB view details)

Uploaded Python 3

File details

Details for the file baidurtc-0.0.1.tar.gz.

File metadata

  • Download URL: baidurtc-0.0.1.tar.gz
  • Upload date:
  • Size: 38.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for baidurtc-0.0.1.tar.gz
Algorithm Hash digest
SHA256 83303ce28ca87439ac221e0903f0998cfeedf9bee94837c64bfa5d2f867a98de
MD5 e7704aefecc910322d18e7fa2147e66c
BLAKE2b-256 f28102fd803f17d64df07f88b95d7419fdcfc81e233c271cf62cd097247c0047

See more details on using hashes here.

File details

Details for the file baidurtc-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: baidurtc-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 36.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for baidurtc-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 760c39b51c2478a4f4dd0e15a8844676611bf6d42445c9ca9c98ee57013497ba
MD5 44293070f6a20fc5ca0c48bef1233a67
BLAKE2b-256 3de13c6968b3a9a91f633d9d87f131e80dd7f51be87a6d4af6aaf33a193fd4a9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page