虚拟背景
本文档将介绍如何在通话中实现虚拟背景功能。
原始摄像头 | 背景虚化 | 背景图片 |
![]() | ![]() | ![]() |
前提条件
价格请参见 RTC-Engine 套餐包。
TRTC SDK 版本须 ≥ 5.5 。
各平台系统及配置要求如下:
实现步骤
部署静态资源
本插件依赖部分静态资源文件。为确保浏览器能够正常加载和运行这些文件,请按以下步骤操作:
1. 将
node_modules/trtc-sdk-v5/assets 目录发布到 CDN 或静态资源服务器。2. 在创建
trtc 实例时,将您的 CDN URL 传递给 assetsPath 参数,例如:TRTC.create({ assetsPath: 'https://xxxx/assets' })。SDK 将根据需要加载相关资源文件。注意:
如果您的版本低于
v5.10.0,需下载并解压 assets.zip,然后发布到 CDN 或静态资源服务器。如果目录中文件的主机 URL 与 Web 应用的主机 URL 不同,则需要为文件域名开启 CORS 策略。
请勿将目录文件置于 HTTP 服务下,因为在 HTTPS 域名下加载 HTTP 资源会被浏览器安全策略阻止。
检查浏览器支持(v5.8.1+)
import { VirtualBackground } from 'trtc-sdk-v5/plugins/video-effect/virtual-background';if (!VirtualBackground.isSupported()) {// 当前浏览器不支持虚拟背景}
注册插件
import { VirtualBackground } from 'trtc-sdk-v5/plugins/video-effect/virtual-background';const trtc = TRTC.create({ plugins: [VirtualBackground], assets: 'https://xxxx/assets' });
开启本地摄像头
await trtc.startLocalVideo();
开启虚拟背景插件
await trtc.startPlugin('VirtualBackground', {sdkAppId: 123123,userId: 'userId_123',userSig: 'your_userSig'});
按需更新参数
// 切换到图片背景await trtc.updatePlugin('VirtualBackground', {type: 'image',src: 'https://picsum.photos/seed/picsum/200/300'});
关闭虚拟背景
await trtc.stopPlugin('VirtualBackground');
API 文档
trtc.startPlugin('VirtualBackground', options)
用于开启虚拟背景。
参数说明
参数名 | 类型 | 属性 | 说明 |
sdkAppId | number | 必填 | 当前应用的 App ID。 |
userId | string | 必填 | 当前用户 ID。 |
userSig | string | 必填 | 用户 ID 对应的 UserSig。 |
type | string | 可选 | image 图片背景。blur 背景虚化(默认值)。 |
src | string | 可选 | 图片 URL。当 type 为 image 时必填。 |
enableFaceCentering | boolean | 可选 | false(默认),设为 true 可开启人脸居中功能。 自 v5.11.0+ 起支持。 |
enableEffectOptimization | boolean | 可选 | false(默认),设为 true 可减少人物周边的黑边和锯齿。 实验性功能。 目前仅在 PC 端支持,自 v5.13.0+ 起支持。 |
示例:
await trtc.startPlugin('VirtualBackground', {sdkAppId: 123123,userId: 'userId_123',userSig: 'your_userSig',type: 'image',src: 'https://picsum.photos/seed/picsum/200/300'});
trtc.updatePlugin('VirtualBackground', options)
允许修改虚拟背景参数。
参数说明
参数名 | 类型 | 属性 | 说明 |
type | string | 必填 | image 图片背景。blur 背景虚化。 |
src | string | 当 type 为 image 时必填 | 图片 URL,例如 https://picsum.photos/seed/picsum/200/300。 |
示例:
await trtc.updatePlugin('VirtualBackground', {type: 'blur'});
trtc.stopPlugin('VirtualBackground')
关闭虚拟背景。
常见问题
在 Chrome 中运行 demo 时,视频出现倒置和卡顿?
本插件使用 GPU 加速,需要在浏览器设置中开启硬件加速模式。您可以将
chrome://settings/system 复制粘贴到浏览器地址栏并开启硬件加速模式。设备性能不足时,出现高延迟和渲染问题?
您可以通过监听事件来降低视频分辨率或帧率。
async function onError(error) {const { code } = error;if (code === 10000003 || code === 10000006) {// 降低分辨率和帧率await trtc.updateLocalVideo({option: {profile: '480p_2'},});// await trtc.stopPlugin('VirtualBackground'); // 或者关闭插件}}await trtc.startPlugin('VirtualBackground', {...// 其他参数onError,});



