如何在声网 React Native SDK 中使用虚拟背景

声网 React Native SDK 支持使用虚拟背景啦,用户可以选择纯色或图片作为背景。下面我们会教大家如何用 React Native 绑定图片资源,以及如何选择图片作为虚拟背景。


前期准备

  • 了解 React Native 的基础知识

这个项目需要一个基础的视频通话应用,大家可以使用这个 demo (点击 GitHub 查找源代码),参照 readme 中的使用建议在自己的设备上运行这个应用。下面我们一起来看一下使用虚拟背景的代码。

另外,我们会用到 react-native-image-picker 和 react-native-fs 这两个开源库。大家可以执行 npm i --save react-native-image-picker react-native-fs 把这两个开源库添加到自己的项目中。


使用虚拟背景

this.virtualSource = new VirtualBackgroundSource({ // create the config
    backgroundSourceType: VirtualBackgroundSourceType.Color,
    color: new Color(1, 0, 0), //specify the RGB value
  });
  await this._engine?.enableVirtualBackground(true, this.virtualSource); // enable virtual background

用声网 SDK 选择虚拟背景非常简单:使用配置信息命令在 engine 对象上调用enableVirtualBackground 方法,就可以打开虚拟背景功能,不用担心会出现背景割裂或背景移除等问题。

首先,在 App 类中定义 virtualSource 特性,用来创建和储存配置命令。然后,在状态中添加一个等待布尔值,便于在执行异步代码时禁用“开始呼叫”按钮。

...
export default class App extends Component<Props, State> {
  _engine?: RtcEngine;
  virtualSource: VirtualBackgroundSource; // defining our config
  constructor(props) {
    super(props);
    this.virtualSource = new VirtualBackgroundSource({ // initializing the config
      backgroundSourceType: VirtualBackgroundSourceType.Color,
      color: new Color(1, 1, 1),
    })
    this.state = {
      appId: '<YourAgoraAppID>',
      waiting: true, // add waiting boolean to the state
      ...
...
// create a function to set the config for using a color
useColor = () => {
    let color = new Color(255, 0, 0);
    this.virtualSource = new VirtualBackgroundSource({
      backgroundSourceType: VirtualBackgroundSourceType.Color,
      color: color,
    });
    this.setState({waiting: false});
  }
...

接下来,定义 useColor 函数,该函数使用 Color 类构造函数,使用传递给它的红色、绿色和蓝色值(颜色区间为 0-255)来创建颜色对象。然后,更新 virtualSource 特性和用户状态。


背景模糊

useBlur = () => {
    this.virtualSource = new VirtualBackgroundSource({
      backgroundSourceType: VirtualBackgroundSourceType.Blur,
      blur_degree: VirtualBackgroundBlurDegree.Medium
    });
    this.setState({waiting: false});
  }

在绑定图片前,先将图片复制到项目目录中,然后使用相应的语法来引用它。大家可以在用 RNFS 测试时,用图片的 URI 将图片下载下来。接下来,用图片的绝对路径更新配置命令的源码特性。


使用本地图片作为虚拟背景

...
pickImage = async () => {
    this.setState({waiting: true});
    await launchImageLibrary({ mediaType: 'photo' }, async (res) => {
      if (res.assets) {
        let uri = res.assets[0].uri;
        if (uri) {
          if(Platform.OS === 'android') {
            await RNFS.copyFile(uri, `${RNFS.DocumentDirectoryPath}/img.png`);
          } else if (Platform.OS === 'ios') {
            await RNFS.downloadFile({ fromUrl: uri, toFile: `${RNFS.DocumentDirectoryPath}/img.png` })
          }
          this.virtualSource = new VirtualBackgroundSource({
            backgroundSourceType: VirtualBackgroundSourceType.Img,
            source: `${RNFS.DocumentDirectoryPath}/img.png`,
          });
        }
      }
    });
    this.setState({waiting: false});
  }
  ...

我们可以用 react-native-image-picker 中的 launchImageLibrary 访问图片 URI。本文在 OS 系统中访问图片,把图片的绝对路径传递给配置命令。

最后,更新 startCall 函数,在加入频道前打开虚拟背景:

...
startCall = async () => {
    await this._engine?.enableVirtualBackground(true, this.virtualSource); // enable virtual background with the latest config
    await this._engine?.joinChannel(
      this.state.token,
      this.state.channelName,
      null,
      0
    );
  };
...

总结

有了声网 SDK 和开源库,给视频通话/直播推流应用添加虚拟背景简单多啦。


原文作者:Ekaansh Arora
原文链接:Use Virtual Backgrounds with the Agora React Native SDK
推荐阅读
相关专栏
SDK 教程
163 文章
本专栏仅用于分享音视频相关的技术文章,与其他开发者和声网 研发团队交流、分享行业前沿技术、资讯。发帖前,请参考「社区发帖指南」,方便您更好的展示所发表的文章和内容。