npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@yuliangz/digital-human-charge

v1.0.32

Published

数字人真人接管 SDK

Readme

数字人真人接管 SDK

这是一个用于实现数字人真人接管功能的 TypeScript SDK。通过 WebSocket 和 BRTC 技术,开发者可以轻松实现音频流驱动数字人的语音和嘴型动作。

安装

使用 npm 安装:

npm install @yuliangz/digital-human-charge

使用方法

基础配置

import { DigitalHumanCharge } from "@yuliangz/digital-human-charge";

const config = {
  wsUrl: "wss://your-digital-human-server.com", // ws连接地址
  apiTimeout: 15000, // API调用超时时间(毫秒),默认15000ms
  reconnectInterval: 15000, // 重连间隔时间(毫秒),默认15000ms
  maxReconnectAttempts: 3, // 最大重连次数,默认3次
  logRecordServiceUrl: "https://your-log-service.com/api/logs", // 日志记录服务地址,可选
  dhConfig: {
    appId: "your-app-id", // 必填,应用ID
    appKey: "your-app-key", // 必填,应用密钥
  },
};

const dhc = new DigitalHumanCharge(config);

初始化 SDK

try {
  // 初始化WebSocket连接,webSocket连接是数字人内部进行消息传递。
  await dhc.initSDK();
  console.log("Connected to server");
} catch (error) {
  console.error("Connected failed:", error);
}

发送连接消息进行初始化数字人

try {
  // 发送连接消息进行初始化数字人。
  // 若场景已在终端渲染数字人,由后台进行真人接管,不需要执行此方法,例如已在iframe集成数字人,那么进行真人接管不需要执行此方法。
  // 若不存在数字人,例如云上交行真人接管场景,需要先创建一个数字人,然后接管数字人,需要执行此方法。
  await dhc.sendConnectMsg();
  console.log("Digital human initialized");
} catch (error) {
  console.error("Digital human initialize failed:", error);
}

加入百度 RTC 房间

try {
  // 加入百度RTC房间,建立音视频连接
  // 无论通过是iframe的创建的数字人,或者web-sdk创建的数字人,或者使用dhc.sendConnectMsg()创建数字人,数字人都会加入到brtc房间中,我们作为本地用户加入brtc房间,数字人相对的是远端用户。加入brtc房间后我们可以拿到远端数字人的音视频流。
  await dhc.joinBrtcRoom();
  console.log("Joined BRTC room successfully");
} catch (error) {
  console.error("Failed to join BRTC room:", error);
}

获取数字人音视频流对象 mediaStream

try {
  // 获取远端数字人音视频流
  // 在加入brtc房间后,我们可以拿到远端数字人的流,用于在页面上渲染数字人等。
  const mediaStream = await dhc.getMediaStream();
  console.log("Got digital human media stream:", mediaStream);
} catch (error) {
  console.error("Failed to get digital human media stream:", error);
}

开始真人接管

try {
  // 发送websocket消息,通知数字人我们要进行真人接管
  // 必须要先完成webSocket连接并加入brtc房间,发送消息到数字人中控服务后,我们本地用户在brtc房间的音频流会自动用于驱动数字人说话。
  await dhc.startVoiceCharge();
  console.log("Voice charge started");
} catch (error) {
  console.error("Failed to start voice charge:", error);
}

停止真人接管

try {
  // 发送websocket消息,通知数字人结束真人接管
  await dhc.stopVoiceCharge();
  console.log("Voice charge stopped");
} catch (error) {
  console.error("Failed to stop voice charge:", error);
}

静音本地麦克风

try {
  // 静音本地麦克风,停止向数字人发送音频
  await dhc.mute();
  console.log("Microphone muted");
} catch (error) {
  console.error("Failed to mute microphone:", error);
}

取消静音本地麦克风

try {
  // 取消静音本地麦克风,恢复向数字人发送音频
  await dhc.unmute();
  console.log("Microphone unmuted");
} catch (error) {
  console.error("Failed to unmute microphone:", error);
}

销毁 SDK

try {
  // 销毁sdk,终止ws连接,终止真人接管,退出brtc房间
  await dhc.destroySDK();
  console.log("SDK destroyed");
} catch (error) {
  console.error("Failed to destroy SDK:", error);
}

事件监听

dhc.on("websocketOpened", () => {
  // websocket建立成功
  // 执行dhc.initSDK(),会建立一个websocket连接,连接建立成功时,触发该事件
  console.log("WebSocket connection opened");
});

dhc.on("websocketClosed", () => {
  // websocket连接已关闭
  // 执行dhc.destroySDK()或者出现异常错误导致websocket连接断开,触发该事件
  console.log("WebSocket connection closed");
});

dhc.on("initialized", (data) => {
  // 数字人初始化成功
  // 执行dhc.sendConnectMsg()成功时,触发该事件,data是本次初始化数字人使用的参数
  console.log("Digital human initialized:", data);
});

dhc.on("brtcStarted", (config) => {
  // 加入brtc房间成功
  // 执行dhc.joinBrtcRoom()成功时,触发该事件,config是本次进入brtc房间使用的参数
  console.log("BRTC started with config:", config);
});

dhc.on("remoteVideoOn", (id) => {
  // 远端视频流到达的回调,例如数字人属于远端视频流
  console.log("Remote video is on:", id);
});

dhc.on("remoteVideoOff", (id) => {
  // 远端视频流离开的回调,例如数字人属于远端视频流
  console.log("Remote video is off:", id);
});

dhc.on("voiceChargeStarted", (data) => {
  // 真人接管开始时,触发此事件
  console.log("Voice charge started:", data);
});

dhc.on("voiceChargeStopped", (data) => {
  // 真人接管结束时,触发此事件
  console.log("Voice charge stopped:", data);
});

dhc.on("localVideoPublishing", () => {
  // 本地视频开始发布的回调
  console.log("Local video is publishing");
});

dhc.on("localVideoPublishedOk", () => {
  // 本地视频成功发布的回调
  console.log("Local video published successfully");
});

dhc.on("userEventJoinedRoom", (id, display, attribute) => {
  // 用户加入房间的事件,此时用户还没有发布流
  console.log("User joined room:", id, display, attribute);
});

dhc.on("userEventLeavingRoom", (id, display) => {
  // 用户离开房间,用户已经关闭了流或者没有发布过流
  console.log("User leaving room:", id, display);
});

dhc.on("reconnecting", (attempt) => {
  // 正在重新连接事件
  console.log("Reconnecting attempt:", attempt);
});

dhc.on("reconnected", () => {
  // 重连成功事件
  console.log("Reconnected successfully");
});

dhc.on("reconnectFailed", (error) => {
  // 重连失败事件
  console.error("Reconnect failed:", error);
});

dhc.on("error", (error) => {
  switch (error.name) {
    case "DIGITAL_HUMAN_INIT_FAILED":
      // 初始化数字人失败,执行dhc.sendConnectMsg()失败时抛出错误,也可以直接在catch里捕获错误
      console.error("Digital human initialization failed:", error);
      break;
    case "BRTC_START_FAILED":
      // BRTC 启动失败,执行dhc.joinBrtcRoom()失败时抛出错误,也可以直接在catch里捕获错误
      console.error("BRTC start failed:", error);
      break;
    case "BRTC_DESTROYED":
      // BRTC的sdk运行过程中内部出现异常或出现错误时,触发此错误事件
      console.error("BRTC destroyed:", error);
      break;
    default:
      console.error("Unknown error:", error);
  }
});

事件监听器的移除

SDK 提供了多种方式来移除事件监听器:

移除特定事件的特定监听器

const myListener = (data) => {
  console.log("Received data:", data);
};

// 添加监听器
dhc.on("initialized", myListener);

// 移除特定监听器
dhc.off("initialized", myListener);

移除特定事件的所有监听器

// 移除特定事件的所有监听器
dhc.off("initialized");

移除所有事件的所有监听器

// 移除所有事件的所有监听器
dhc.removeAllListeners();

API 文档

DigitalHumanChargeConfig

配置接口:

interface DigitalHumanChargeConfig {
  wsUrl: string; // WebSocket 服务器地址
  apiTimeout?: number; // API调用超时时间(毫秒),默认5000ms
  reconnectInterval?: number; // 重连间隔时间(毫秒),默认5000ms
  maxReconnectAttempts?: number; // 最大重连次数,默认3次
  logRecordServiceUrl?: string; // 日志记录服务地址,可选
  dhConfig: {
    // 数字人配置
    appId: string; // 必填,应用 ID
    appKey: string; // 必填,应用密钥
    project?: string; // 可选,项目ID,默认值:"0001"
    parameters?: {
      // 可选,数字人参数配置
      roomName?: string; // 可选,房间名称,默认随机生成
      resolutionHeight?: string; // 可选,画布高度,默认值:"960"
      resolutionWidth?: string; // 可选,画布宽度,默认值:"540"
      background_image_url?: string; // 可选,背景图片URL
      rtmpUrl?: string; // 可选,RTMP推流地址
      deviceType?: string; // 可选,设备类型
      pullAudioFromRtc?: string; // 可选,是否从RTC拉取音频,默认:"true"
      x264_param_rc_i_bitrate?: string; // 可选,x264编码参数比特率,默认:"1000"
      x264_param_rc_i_buffer_size?: string; // 可选,x264编码参数缓冲区大小
      x264_param_rc_f_ip_factor?: string; // 可选,x264编码参数I帧间隔
      x264_param_apply_profile?: string; // 可选,x264编码参数应用配置文件
      x264_param_i_level_idc?: string; // 可选,x264编码参数级别ID
      pickAudioMode?: string; // 可选,音频采集模式,默认:"free"
      usingAudio?: string; // 可选,是否使用音频,默认:"true"
    };
  };
  brtcConfig?: {
    // BRTC 配置,可选
    server?: string; // RTC 服务器地址,默认:"wss://rtc.exp.bcelive.com/janus"
    appid?: string; // 百度派发的AppID
    token?: string; // app server 派发的token字符串
    roomname?: string; // 房间名称
    userid?: string; // 用户ID
    displayname?: string; // 显示名称
    remotevideoviewid?: string; // 显示远端视频的DOM元素ID
    localvideoviewid?: string; // 显示本地摄像头视频的DOM元素ID
    showvideobps?: boolean; // 是否显示视频带宽值,默认:true
    shownovideo?: boolean; // 不存在视频时的显示提示,默认:true
    showspinner?: boolean; // 是否显示加载过程,默认:true
    aspublisher?: boolean; // 是否是发布者,默认:true
    usingdatachannel?: boolean; // 是否使用数据通道,默认:true
    usingvideo?: boolean; // 是否使用本地视频设备,默认:true
    usingaudio?: boolean; // 是否使用本地音频设备,默认:true
    sharescreen?: boolean; // 是否是屏幕共享,默认:false
    videodeviceid?: string; // 视频设备ID,默认使用摄像头
    rtmpserver?: string; // 直播转推流的地址,格式:"rtmp://server/stream"
    rtmpmixtemplate?: string; // 直播转推模版
    rtmpmix?: boolean; // 直播转推是否混流,默认:false
    rtmpmixlayoutindex?: string; // 转推混流ID标识
    autosubscribe?: boolean; // 是否自动订阅流,默认:true
    autopublish?: boolean; // 是否自动发布流,默认:true
    waitpermissiontimeoutms?: number; // 等待权限超时大小,默认:180000毫秒
    candidateip?: string; // 代理服务器的IP
    mediaserverip?: string; // 代理指向的媒体服务器IP
    videocodec?: "h264" | "vp8" | "h263" | "vp9"; // 视频编码类型配置,默认:h264
    videoprofile?: "lowres" | "stdres" | "hires" | "fhdres" | "4kres" | string; // 本地摄像头视频配置
    bitrate?: number; // 摄像头编码的码率,单位kbps,720p视频建议1500
    screenbitrate?: number; // 屏幕共享的码率,默认:1500kbps
    remotevideoon?: (arg0: any) => void; // 远端视频流回调
    remotevideooff?: (arg0: any) => void; // 远端视频流关闭回调
    remotevideocoming?: (arg0: any) => void; // 远端视频流进入回调
    remotevideoleaving?: (arg0: any) => void; // 远端视频流离开回调
    localvideopublishing?: (arg0: any) => void; // 本地视频流发布中回调
    localvideopublished_ok?: (arg0: any) => void; // 本地视频流发布成功回调
    onmessage?: (arg0: any) => void;
    onattribute?: (arg0: any) => void;
    userevent?: (arg0: any) => void;
    userevent_joinedroom?: (arg0: any) => void;
    userevent_leavingroom?: (arg0: any) => void;
    debuglevel?: boolean | string | string[]; // 调试信息级别,默认:true
    onlocalstream?: (stream: MediaStream, name: string) => void; // 本地视频流回调
    onlocalstream_end?: (name: string) => void; // 本地视频流关闭回调
    success?: () => void; // 启动成功回调
    error?: (error: Error) => void; // 启动失败或运行错误回调
    destroyed?: (error: Error) => void; // 运行错误被销毁回调
  };
}

// 所有可选参数的默认值
const defaultConfig = {
  apiTimeout: 15000,
  reconnectInterval: 15000,
  maxReconnectAttempts: 3,
  dhConfig: {
    project: "0001",
    parameters: {
      roomName: `room_${Date.now()}_${uuidv4().substring(0, 8)}`,
      resolutionHeight: "960",
      resolutionWidth: "540",
      rtmpUrl: "",
      deviceType: "",
      pullAudioFromRtc: "true",
      x264_param_rc_i_bitrate: "1000",
      x264_param_rc_i_buffer_size: "",
      x264_param_rc_f_ip_factor: "",
      x264_param_apply_profile: "",
      x264_param_i_level_idc: "",
      pickAudioMode: "free",
      usingAudio: "true",
    },
  },
};

方法

  • initSDK(): 初始化 WebSocket 连接
  • sendConnectMsg(): 发送连接消息,初始化数字人
  • joinBrtcRoom(): 加入百度 RTC 房间,建立音视频连接
  • startVoiceCharge(): 开始真人接管
  • stopVoiceCharge(): 停止真人接管
  • mute(): 静音本地麦克风
  • unmute(): 取消静音本地麦克风
  • getMediaStream(): 获取数字人媒体流
  • getStatus(): 获取当前连接状态
  • restart(): 重新连接
  • getBrtcInstance(): 获取BRTC实例
  • destroySDK(): 销毁 SDK,断开连接

事件

interface DigitalHumanChargeEvents {
  websocketOpened: () => void; // WebSocket连接打开
  websocketClosed: () => void; // WebSocket连接关闭
  initialized: (data: any) => void; // 数字人初始化完成
  brtcStarted: (config: any) => void; // 百度RTC启动成功
  remoteVideoOn: (data?: any) => void; // 远程视频流开启
  remoteVideoOff: (data?: any) => void; // 远程视频流关闭
  voiceChargeStarted: (data?: any) => void; // 真人接管开始
  voiceChargeStopped: (data?: any) => void; // 真人接管停止
  localVideoPublishing: () => void; // 本地视频开始发布
  localVideoPublishedOk: () => void; // 本地视频发布成功
  userEventJoinedRoom: (id: any, display: any, attribute: any) => void; // 用户加入房间
  userEventLeavingRoom: (id: any, display: any) => void; // 用户离开房间
  reconnecting: (attempt: number) => void; // 正在重新连接事件
  reconnected: () => void; // 重连成功事件
  reconnectFailed: (error: Error) => void; // 重连失败事件
  error: (error: any) => void; // 发生错误时触发
}

错误处理

SDK 定义了以下错误类型:

  • CONNECT_FAILED: 连接失败
  • BRTC_START_FAILED: 百度 RTC 启动失败
  • BRTC_DESTROYED: 百度 RTC 被销毁

许可证

MIT