C++ 在 Unreal 中为游戏增加实时音视频互动的教程详解

2020-05-29 11:02:26于丽

增加 StopCall 功能

根据你的场景需要,通过调用 leaveChannel 方法来结束通话,比如当要结束通话的时候,当你需要关闭应用的时候,或是当你的应用运行于后台的时候。调用 nullptr 作为实参的 registerVideoFrameObserver,用来取消 VideoFrameObserver的注册。

//VideoCall.cpp
void VideoCall::StopCall()
{
 if (!RtcEnginePtr)
 {
 return;
 }
 auto ConnectionState = RtcEnginePtr->getConnectionState();
 if (agora::rtc::CONNECTION_STATE_DISCONNECTED != ConnectionState)
 {
 int nRet = RtcEnginePtr->leaveChannel();
 if (nRet < 0)
 {
 UE_LOG(LogTemp, Warning, TEXT("leaveChannel ret: %d"), nRet);
 }
 if (MediaEnginePtr)
 {
 MediaEnginePtr->registerVideoFrameObserver(nullptr);
 }
 }
}

创建 Video 方法

这些方法是用来管理视频的。

加 EnableVideo() 方法

EnableVideo() 会启用本示例中的视频。初始化 nRet,值为 0。如果 bEnable 为 true,则通过 RtcEnginePtr->enableVideo() 启用视频。否则,通过 RtcEnginePtr->disableVideo() 关闭视频。

//VideoCall.cpp
bool VideoCall::EnableVideo(bool bEnable)
{
 if (!RtcEnginePtr)
 {
 return false;
 }
 int nRet = 0;
 if (bEnable)
 nRet = RtcEnginePtr->enableVideo();
 else
 nRet = RtcEnginePtr->disableVideo();
 return nRet == 0 ? true : false;
}

增加 MuteLocalVideo() 方法

MuteLocalVideo() 方法负责开启或关闭本地视频。在其余方法完成运行之前,需要保证 RtcEnginePtr 不为 nullptr。如果可以成功mute 或 unmute 本地视频,那么把 bLocalVideoMuted 设置为 bMuted。

//VideoCall.cpp
bool VideoCall::MuteLocalVideo(bool bMuted)
{
 if (!RtcEnginePtr)
 {
 return false;
 }
 int ret = RtcEnginePtr->muteLocalVideoStream(bMuted);
 if (ret == 0)
 bLocalVideoMuted = bMuted;
 return ret == 0 ? true : false;
}

增加 IsLocalVideoMuted() 方法

IsLocalVideoMuted() 方法的作用是,当本地视频开启或关闭的时候,返回 bLocalVideoMuted。

//VideoCall.cpp
bool VideoCall::IsLocalVideoMuted()
{
 return bLocalVideoMuted;
}

创建音频相关的方法

这些方法是用来管理音频的。

添加 MuteLocalAudio() 方法

MuteLocalAudio()用于 mute 或 unmute 本地音频:

//VideoCall.cpp
bool VideoCall::MuteLocalAudio(bool bMuted)
{
 if (!RtcEnginePtr)
 {
 return false;
 }
 int ret = RtcEnginePtr->muteLocalAudioStream(bMuted);
 if (ret == 0)
 bLocalAudioMuted = bMuted;
 return ret == 0 ? true : false;
}

增加 IsLocalAudioMuted() 方法

IsLocalAudioMuted()方法的作用是,当 mute 或 unmute 本地音频的时候,返回 bLocalAudioMuted。

//VideoCall.cpp
bool VideoCall::IsLocalAudioMuted()
{
 return bLocalAudioMuted;
}

创建 GUI

接下来就是要为一对一对话创建用户交互界面了,包括: