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

时间:2021-09-28 18:12:16

我们已经上线了 Agora Unreal SDK,提供了支持 Blueprint 和 C++ 的两个版本 SDK。我们分享了 如何基于 Blueprint 在游戏中创建实时音视频功能 。在本文中,我们来分享如何基于声网 Agora Unreal SDK C++版本,在游戏中实现实时音视频功能。

本篇教程较长,建议在 Web 浏览器端浏览,体验更好。

准备工作

需要的开发环境和需要准备的与 Blueprint 一样:

  • Unreal 4.34 以上版本
  • Visual Studio 或 Xcode(版本根据 Unreal 配置要求而定)
  • 运行 Windows 7 以上系统的 PC 或 一台 Mac
  • Agora 注册账号一枚(免费注册,见官网 Agora.io)
  • 如果你的企业网络存在防火墙,请在声网文档中心搜索「应用企业防火墙限制」,进行配置。

新建项目

如果你已经有 Unreal 项目了,可以跳过这一步。在 Unreal 中创建一个 C++类型的项目。

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

确保在 [your_project]/Source/[project_name]/[project_name].Build.cs文件的 PrivateDependencyModuleNames一行,去掉注释。Unreal 默认是将它注释掉的,这会导致在编译的时候报错。

  1. // Uncomment if you are using Slate UI
  2. PrivateDependencyModuleNames.AddRange(new string[] { "UMG", "Slate", "SlateCore" });

接下来我们在项目中集成 Agora SDK

1.将 SDK 复制到这个路径下 [your_project]/Plugins

2.把插件依赖添加到[your_project]/Source/[project_name]/[project_name].Build.cs文件的私有依赖(Private Dependencies)部分 PrivateDependencyModuleNames.AddRange(new string[] { "AgoraPlugin", "AgoraBlueprintable" });

3.重启 Unreal

4.点击 Edit->Plugin,在分类中找到 Project->Other,确定插件已经生效

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

创建新的 Level

接下来我们将创建一个新的 Level,在那里建立我们的游戏环境。有几种不同的方法可以创建一个新的 Level,我们将使用文件菜单的方法,其中列出了关卡选择选项。

在虚幻编辑器里面,点击文件菜单选项,然后选择新建 Level......

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

然后会打开一个新的对话框 。

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

选择Empty Level ,然后指定一个存储的路径。

创建核心类

在这里我们要创建两个类:VideoFrameObserver 和VideoCall C++ Class。他们会负责与 Agora SDK 进行通信。

首先是 VideoFrameObserver。VideoFrameObserver 执行的是 agora::media::IVideoFrameObserver。这个方法在 VideoFrameObserver 类中负责管理视频帧的回调。它是用 registerVideoFrameObserver 在 agora::media::IMediaEngine 中注册的。

在 Unreal 编辑器中,选择 File->Add New C++ Class。

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

父类谁定为 None,然后点击下一步。

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

为 VideoFrameObserver明明,然后选择 Create Class。

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

创建 VideoFrameObserver 类接口。

打开 VideoFrameObserver.h 文件然后添加如下代码:

  1. //VideoFrameObserver.h
  2. #include "CoreMinimal.h"
  3. #include <functional>
  4. #include "AgoraMediaEngine.h"
  5. class AGORAVIDEOCALL_API VideoFrameObserver : public agora::media::IVideoFrameObserver
  6. {
  7. public:
  8. virtual ~VideoFrameObserver() = default;
  9. public:
  10. bool onCaptureVideoFrame(VideoFrame& videoFrame) override;
  11. bool onRenderVideoFrame(unsigned int uid, VideoFrame& videoFrame) override;
  12. void setOnCaptureVideoFrameCallback(
  13. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> callback);
  14. void setOnRenderVideoFrameCallback(
  15. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> callback);
  16. virtual VIDEO_FRAME_TYPE getVideoFormatPreference() override { return FRAME_TYPE_RGBA; }
  17. private:
  18. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnCaptureVideoFrame;
  19. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnRenderVideoFrame;
  20. };

AGORAVIDEOCALL_API 是项目依赖的定义,而不是由Unreal 生成的你自己的定义。

重写onCaptureVideoFrame/onRenderVideoFrame方法

onCaptureVideoFrame 会获取到摄像头捕获的画面,转换为 ARGB 格式并触发 OnCaptureVideoFrame 回调。

onRenderVideoFrame 讲收到的特定用户画面转换为 ARGB 格式,然后触发 onRenderVideoFrame 回调。

  1. //VideoFrameObserver.cpp
  2. bool VideoFrameObserver::onCaptureVideoFrame(VideoFrame& Frame)
  3. {
  4. const auto BufferSize = Frame.yStride*Frame.height;
  5. if (OnCaptureVideoFrame)
  6. {
  7. OnCaptureVideoFrame( static_cast< uint8_t* >( Frame.yBuffer ), Frame.width, Frame.height, BufferSize );
  8. }
  9. return true;
  10. }
  11. bool VideoFrameObserver::onRenderVideoFrame(unsigned int uid, VideoFrame& Frame)
  12. {
  13. const auto BufferSize = Frame.yStride*Frame.height;
  14. if (OnRenderVideoFrame)
  15. {
  16. OnRenderVideoFrame( static_cast<uint8_t*>(Frame.yBuffer), Frame.width, Frame.height, BufferSize );
  17. }
  18. return true;
  19. }

增加setOnCaptureVideoFrameCallback/setOnRenderVideoFrameCallback方法。

设定回调,用来获取摄像头获取到的本地画面和远端的画面。

  1. //VideoFrameObserver.cpp
  2. void VideoFrameObserver::setOnCaptureVideoFrameCallback(
  3. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> Callback)
  4. {
  5. OnCaptureVideoFrame = Callback;
  6. }
  7. void VideoFrameObserver::setOnRenderVideoFrameCallback(
  8. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> Callback)
  9. {
  10. OnRenderVideoFrame = Callback;
  11. }

创建视频通话C++类

VideoCall 类管理与 Agora SDK 的通信。需要创建多个方法和接口。

创建类接口

回到 Unreal 编辑器,再创建一个新的 C++类,命名为 VideoCall.h。然后进入VideoCall.h文件,添加一下接口:

  1. //VideoCall.h
  2. #pragma once
  3. #include "CoreMinimal.h"
  4. #include <functional>
  5. #include <vector>
  6. #include "AgoraRtcEngine.h"
  7. #include "AgoraMediaEngine.h"
  8. class VideoFrameObserver;
  9. class AGORAVIDEOCALL_API VideoCall
  10. {
  11. public:
  12. VideoCall();
  13. ~VideoCall();
  14. FString GetVersion() const;
  15. void RegisterOnLocalFrameCallback(
  16. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnLocalFrameCallback);
  17. void RegisterOnRemoteFrameCallback(
  18. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnRemoteFrameCallback);
  19. void StartCall(
  20. const FString& ChannelName,
  21. const FString& EncryptionKey,
  22. const FString& EncryptionType);
  23. void StopCall();
  24. bool MuteLocalAudio(bool bMuted = true);
  25. bool IsLocalAudioMuted();
  26. bool MuteLocalVideo(bool bMuted = true);
  27. bool IsLocalVideoMuted();
  28. bool EnableVideo(bool bEnable = true);
  29. private:
  30. void InitAgora();
  31. private:
  32. TSharedPtr<agora::rtc::ue4::AgoraRtcEngine> RtcEnginePtr;
  33. TSharedPtr<agora::media::ue4::AgoraMediaEngine> MediaEnginePtr;
  34. TUniquePtr<VideoFrameObserver> VideoFrameObserverPtr;
  35. //callback
  36. //data, w, h, size
  37. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnLocalFrameCallback;
  38. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnRemoteFrameCallback;
  39. bool bLocalAudioMuted = false;
  40. bool bLocalVideoMuted = false;
  41. };

创建初始化方法

进入 VideoCall.cpp 文件,添加以下代码:

  1. //VideoCall.cpp
  2. #include "AgoraVideoDeviceManager.h"
  3. #include "AgoraAudioDeviceManager.h"
  4. #include "MediaShaders.h"
  5. #include "VideoFrameObserver.h"

用agora::rtc::ue4::AgoraRtcEngine::createAgoraRtcEngine()创建引擎,初始化 RtcEnginePtr 变量。创建一个RtcEngineContext对象,然后在ctx.eventHandler 和ctx.appId中设定 event handler 和 App ID 。初始化引擎,并创建AgoraMediaEngine对象,初始化 MediaEnginePtr。

  1. //VideoCall.cpp
  2. VideoCall::VideoCall()
  3. {
  4. InitAgora();
  5. }
  6. VideoCall::~VideoCall()
  7. {
  8. StopCall();
  9. }
  10. void VideoCall::InitAgora()
  11. {
  12. RtcEnginePtr = TSharedPtr<agora::rtc::ue4::AgoraRtcEngine>(agora::rtc::ue4::AgoraRtcEngine::createAgoraRtcEngine());
  13. static agora::rtc::RtcEngineContext ctx;
  14. ctx.appId = "aab8b8f5a8cd4469a63042fcfafe7063";
  15. ctx.eventHandler = new agora::rtc::IRtcEngineEventHandler();
  16. int ret = RtcEnginePtr->initialize(ctx);
  17. if (ret < 0)
  18. {
  19. UE_LOG(LogTemp, Warning, TEXT("RtcEngine initialize ret: %d"), ret);
  20. }
  21. MediaEnginePtr = TSharedPtr<agora::media::ue4::AgoraMediaEngine>(agora::media::ue4::AgoraMediaEngine::Create(RtcEnginePtr.Get()));
  22. }
  23. FString VideoCall::GetVersion() const
  24. {
  25. if (!RtcEnginePtr)
  26. {
  27. return "";
  28. }
  29. int build = 0;
  30. const char* version = RtcEnginePtr->getVersion(&build);
  31. return FString(ANSI_TO_TCHAR(version));
  32. }

创建回调方法

接下来创建回调方法,返回本地和远端的视频帧

  1. //VideoCall.cpp
  2. void VideoCall::RegisterOnLocalFrameCallback(
  3. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnFrameCallback)
  4. {
  5. OnLocalFrameCallback = std::move(OnFrameCallback);
  6. }
  7. void VideoCall::RegisterOnRemoteFrameCallback(
  8. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnFrameCallback)
  9. {
  10. OnRemoteFrameCallback = std::move(OnFrameCallback);
  11. }

创建呼叫方法

我们需要利用这个方法来实现“加入频道”和“离开频道”。

增加 StartCall

首先创建 VideoFrameObserver 对象,然后根据你的场景来设置以下回调。

  • OnLocalFrameCallback:用于 SDK 获取本地摄像头采集到的视频帧。
  • OnRemoteFrameCallback:用于 SDK 获取远端摄像头采集到的视频帧。

在 InitAgora 的 MediaEngine 对象中通过 registerVideoFrameObserver 方法注册 VideoFrameObserver。为了保证 EncryptionType 和 EncryptionKey 不为空,需要先设置 EncryptionMode 和 EncryptionSecret。然后按照你的需要来设置频道参数,并调用 joinChannel。

  1. //VideoCall.cpp
  2. void VideoCall::StartCall(
  3. const FString& ChannelName,
  4. const FString& EncryptionKey,
  5. const FString& EncryptionType)
  6. {
  7. if (!RtcEnginePtr)
  8. {
  9. return;
  10. }
  11. if (MediaEnginePtr)
  12. {
  13. if (!VideoFrameObserverPtr)
  14. {
  15. VideoFrameObserverPtr = MakeUnique<VideoFrameObserver>();
  16. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnCaptureVideoFrameCallback
  17. = [this](std::uint8_t* buffer, std::uint32_t width, std::uint32_t height, std::uint32_t size)
  18. {
  19. if (OnLocalFrameCallback)
  20. {
  21. OnLocalFrameCallback(buffer, width, height, size);
  22. }
  23. else { UE_LOG(LogTemp, Warning, TEXT("VideoCall OnLocalFrameCallback isn't set")); }
  24. };
  25. VideoFrameObserverPtr->setOnCaptureVideoFrameCallback(std::move(OnCaptureVideoFrameCallback));
  26. std::function<void(std::uint8_t*, std::uint32_t, std::uint32_t, std::uint32_t)> OnRenderVideoFrameCallback
  27. = [this](std::uint8_t* buffer, std::uint32_t width, std::uint32_t height, std::uint32_t size)
  28. {
  29. if (OnRemoteFrameCallback)
  30. {
  31. OnRemoteFrameCallback(buffer, width, height, size);
  32. }
  33. else { UE_LOG(LogTemp, Warning, TEXT("VideoCall OnRemoteFrameCallback isn't set")); }
  34. };
  35. VideoFrameObserverPtr->setOnRenderVideoFrameCallback(std::move(OnRenderVideoFrameCallback));
  36. }
  37. MediaEnginePtr->registerVideoFrameObserver(VideoFrameObserverPtr.Get());
  38. }
  39. int nRet = RtcEnginePtr->enableVideo();
  40. if (nRet < 0)
  41. {
  42. UE_LOG(LogTemp, Warning, TEXT("enableVideo : %d"), nRet)
  43. }
  44. if (!EncryptionType.IsEmpty() && !EncryptionKey.IsEmpty())
  45. {
  46. if (EncryptionType == "aes-256")
  47. {
  48. RtcEnginePtr->setEncryptionMode("aes-256-xts");
  49. }
  50. else
  51. {
  52. RtcEnginePtr->setEncryptionMode("aes-128-xts");
  53. }
  54. nRet = RtcEnginePtr->setEncryptionSecret(TCHAR_TO_ANSI(*EncryptionKey));
  55. if (nRet < 0)
  56. {
  57. UE_LOG(LogTemp, Warning, TEXT("setEncryptionSecret : %d"), nRet)
  58. }
  59. }
  60. nRet = RtcEnginePtr->setChannelProfile(agora::rtc::CHANNEL_PROFILE_COMMUNICATION);
  61. if (nRet < 0)
  62. {
  63. UE_LOG(LogTemp, Warning, TEXT("setChannelProfile : %d"), nRet)
  64. }
  65. //"demoChannel1";
  66. std::uint32_t nUID = 0;
  67. nRet = RtcEnginePtr->joinChannel(NULL, TCHAR_TO_ANSI(*ChannelName), NULL, nUID);
  68. if (nRet < 0)
  69. {
  70. UE_LOG(LogTemp, Warning, TEXT("joinChannel ret: %d"), nRet);
  71. }
  72. }

增加 StopCall 功能

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

  1. //VideoCall.cpp
  2. void VideoCall::StopCall()
  3. {
  4. if (!RtcEnginePtr)
  5. {
  6. return;
  7. }
  8. auto ConnectionState = RtcEnginePtr->getConnectionState();
  9. if (agora::rtc::CONNECTION_STATE_DISCONNECTED != ConnectionState)
  10. {
  11. int nRet = RtcEnginePtr->leaveChannel();
  12. if (nRet < 0)
  13. {
  14. UE_LOG(LogTemp, Warning, TEXT("leaveChannel ret: %d"), nRet);
  15. }
  16. if (MediaEnginePtr)
  17. {
  18. MediaEnginePtr->registerVideoFrameObserver(nullptr);
  19. }
  20. }
  21. }

创建 Video 方法

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

加 EnableVideo() 方法

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

  1. //VideoCall.cpp
  2. bool VideoCall::EnableVideo(bool bEnable)
  3. {
  4. if (!RtcEnginePtr)
  5. {
  6. return false;
  7. }
  8. int nRet = 0;
  9. if (bEnable)
  10. nRet = RtcEnginePtr->enableVideo();
  11. else
  12. nRet = RtcEnginePtr->disableVideo();
  13. return nRet == 0 ? true : false;
  14. }

增加 MuteLocalVideo() 方法

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

  1. //VideoCall.cpp
  2. bool VideoCall::MuteLocalVideo(bool bMuted)
  3. {
  4. if (!RtcEnginePtr)
  5. {
  6. return false;
  7. }
  8. int ret = RtcEnginePtr->muteLocalVideoStream(bMuted);
  9. if (ret == 0)
  10. bLocalVideoMuted = bMuted;
  11. return ret == 0 ? true : false;
  12. }

增加 IsLocalVideoMuted() 方法

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

  1. //VideoCall.cpp
  2. bool VideoCall::IsLocalVideoMuted()
  3. {
  4. return bLocalVideoMuted;
  5. }

创建音频相关的方法

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

添加 MuteLocalAudio() 方法

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

  1. //VideoCall.cpp
  2. bool VideoCall::MuteLocalAudio(bool bMuted)
  3. {
  4. if (!RtcEnginePtr)
  5. {
  6. return false;
  7. }
  8. int ret = RtcEnginePtr->muteLocalAudioStream(bMuted);
  9. if (ret == 0)
  10. bLocalAudioMuted = bMuted;
  11. return ret == 0 ? true : false;
  12. }

增加 IsLocalAudioMuted() 方法

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

  1. //VideoCall.cpp
  2. bool VideoCall::IsLocalAudioMuted()
  3. {
  4. return bLocalAudioMuted;
  5. }

创建 GUI

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

  • 创建 VideoCallPlayerController
  • 创建 EnterChannelWidget C++ Class
  • 创建 VideoViewWidget C++ Class
  • 创建 VideoCallViewWidget C++ Class
  • 创建 VideoCallWidget C++ Class
  • 创建 BP_EnterChannelWidget blueprint asset
  • 创建 BP_VideoViewWidget Asset
  • 创建 BP_VideoCallViewWidget Asset
  • 创建 BP_VideoCallWidget Asset
  • 创建 BP_VideoCallPlayerController blueprint asset
  • 创建 BP_AgoraVideoCallGameModeBase Asset
  • 修改 Game Mode

创建 VideoCallPlayerController

为了能够将我们的Widget Blueprints添加到Viewport中,我们创建我们的自定义播放器控制器类。

在 "内容浏览器 "中,按 "Add New "按钮,选择 "新建C++类"。在 "添加C++类 "窗口中,勾选 "显示所有类 "按钮,并输入PlayerController。按 "下一步 "按钮,给类命名为 VideoCallPlayerController。按Create Class按钮。

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

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

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

  1. //VideoCallPlayerController.h
  2. #include "CoreMinimal.h"
  3. #include "GameFramework/PlayerController.h"
  4. #include "VideoCallPlayerController.generated.h"
  5. UCLASS()
  6. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  7. {
  8. GENERATED_BODY()
  9. public:
  10. };

这个类是 BP_VideoCallPlayerController 的 Blueprint Asset 的基类,我们将在最后创建。

增加需要的 Include

在 VideoCallPlayerController.h 文件的头部包括了所需的头文件。

  1. //VideoCallPlayerController.h
  2. #include "CoreMinimal.h"
  3. #include "GameFramework/PlayerController.h"
  4. #include "Templates/UniquePtr.h"
  5. #include "VideoCall.h"
  6. #include "VideoCallPlayerController.generated.h"
  7. //VideoCallPlayerController.cpp
  8. #include "Blueprint/UserWidget.h"
  9. #include "EnterChannelWidget.h"
  10. #include "VideoCallWidget.h"

类声明

为下一个类添加转发声明:

  1. //VideoCallPlayerController.h
  2. class UEnterChannelWidget;
  3. class UVideoCallWidget;

稍后我们将跟进其中的两个创建,即 UEnterChannelWidget 和 UVideoCallWidget。

添加成员变量

现在,在编辑器中添加成员引用到 UMG Asset 中。

  1. //VideoCallPlayerController.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  5. {
  6. GENERATED_BODY()
  7. public:
  8. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
  9. TSubclassOf<class UUserWidget> wEnterChannelWidget;
  10. UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Widgets")
  11. TSubclassOf<class UUserWidget> wVideoCallWidget;
  12. ...
  13. };

变量来保持创建后的小部件,以及一个指向VideoCall的指针。

  1. //VideoCallPlayerController.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  5. {
  6. GENERATED_BODY()
  7. public:
  8. ...
  9. UEnterChannelWidget* EnterChannelWidget = nullptr;
  10. UVideoCallWidget* VideoCallWidget = nullptr;
  11. TUniquePtr<VideoCall> VideoCallPtr;
  12. ...
  13. };

覆盖 BeginPlay/EndPlay

  1. //VideoCallPlayerController.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  5. {
  6. GENERATED_BODY()
  1. public:
  2. ...
  3. void BeginPlay() override;
  4. void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
  5. ...
  6. };
  7. //VideoCallPlayerController.cpp
  8. void AVideoCallPlayerController::BeginPlay()
  9. {
  10. Super::BeginPlay();
  11. //initialize wigets
  12. if (wEnterChannelWidget) // Check if the Asset is assigned in the blueprint.
  13. {
  14. // Create the widget and store it.
  15. if (!EnterChannelWidget)
  16. {
  17. EnterChannelWidget = CreateWidget<UEnterChannelWidget>(this, wEnterChannelWidget);
  18. EnterChannelWidget->SetVideoCallPlayerController(this);
  19. }
  20. // now you can use the widget directly since you have a referance for it.
  21. // Extra check to make sure the pointer holds the widget.
  22. if (EnterChannelWidget)
  23. {
  24. //let add it to the view port
  25. EnterChannelWidget->AddToViewport();
  26. }
  27. //Show the Cursor.
  28. bShowMouseCursor = true;
  29. }
  30. if (wVideoCallWidget)
  31. {
  32. if (!VideoCallWidget)
  33. {
  34. VideoCallWidget = CreateWidget<UVideoCallWidget>(this, wVideoCallWidget);
  35. VideoCallWidget->SetVideoCallPlayerController(this);
  36. }
  37. if (VideoCallWidget)
  38. {
  39. VideoCallWidget->AddToViewport();
  40. }
  41. VideoCallWidget->SetVisibility(ESlateVisibility::Collapsed);
  42. }
  43. //create video call and switch on the EnterChannelWidget
  44. VideoCallPtr = MakeUnique<VideoCall>();
  45. FString Version = VideoCallPtr->GetVersion();
  46. Version = "Agora version: " + Version;
  47. EnterChannelWidget->UpdateVersionText(Version);
  48. SwitchOnEnterChannelWidget(std::move(VideoCallPtr));
  49. }
  50. void AVideoCallPlayerController::EndPlay(const EEndPlayReason::Type EndPlayReason)
  51. {
  52. Super::EndPlay(EndPlayReason);
  53. }

这时你可能注意到EnterChannelWidget和VideoCallWidget方法被标记为错误,那是因为它们还没有实现。我们将在接下来的步骤中实现它们。

增加 StartCall/EndCall

  1. //VideoCallPlayerController.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  5. {
  6. GENERATED_BODY()
  7. public:
  8. ...
  9. void StartCall(
  10. TUniquePtr<VideoCall> PassedVideoCallPtr,
  11. const FString& ChannelName,
  12. const FString& EncryptionKey,
  13. const FString& EncryptionType
  14. );
  15. void EndCall(TUniquePtr<VideoCall> PassedVideoCallPtr);
  16. ...
  17. };
  18. //VideoCallPlayerController.cpp
  19. void AVideoCallPlayerController::StartCall(
  20. TUniquePtr<VideoCall> PassedVideoCallPtr,
  21. const FString& ChannelName,
  22. const FString& EncryptionKey,
  23. const FString& EncryptionType)
  24. {
  25. SwitchOnVideoCallWidget(std::move(PassedVideoCallPtr));
  26. VideoCallWidget->OnStartCall(
  27. ChannelName,
  28. EncryptionKey,
  29. EncryptionType);
  30. }
  31. void AVideoCallPlayerController::EndCall(TUniquePtr<VideoCall> PassedVideoCallPtr)
  32. {
  33. SwitchOnEnterChannelWidget(std::move(PassedVideoCallPtr));
  34. }

增加打开另一个小工具的方法

  1. //VideoCallPlayerController.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API AVideoCallPlayerController : public APlayerController
  5. {
  6. GENERATED_BODY()
  7. public:
  8. ...
  9. void SwitchOnEnterChannelWidget(TUniquePtr<VideoCall> PassedVideoCallPtr);
  10. void SwitchOnVideoCallWidget(TUniquePtr<VideoCall> PassedVideoCallPtr);
  11. ...
  12. };
  13. //VideoCallPlayerController.cpp
  14. void AVideoCallPlayerController::SwitchOnEnterChannelWidget(TUniquePtr<VideoCall> PassedVideoCallPtr)
  15. {
  16. if (!EnterChannelWidget)
  17. {
  18. return;
  19. }
  20. EnterChannelWidget->SetVideoCall(std::move(PassedVideoCallPtr));
  21. EnterChannelWidget->SetVisibility(ESlateVisibility::Visible);
  22. }
  23. void AVideoCallPlayerController::SwitchOnVideoCallWidget(TUniquePtr<VideoCall> PassedVideoCallPtr)
  24. {
  25. if (!VideoCallWidget)
  26. {
  27. return;
  28. }
  29. VideoCallWidget->SetVideoCall(std::move(PassedVideoCallPtr));
  30. VideoCallWidget->SetVisibility(ESlateVisibility::Visible);
  31. }

创建 EnterChannelWidget C++类

EnterChannelWidget是负责管理 UI 元素交互的。我们要创建一个新的 UserWidget 类型的类。在内容浏览器中,按Add New按钮,选择New C++类,然后勾选Show All Classes按钮,输入UserWidget。按下 "下一步 "按钮,为类设置一个名称,EnterChannelWidget。

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

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

我们会得到如下代码:

  1. //EnterChannelWidget.h
  2. #include "CoreMinimal.h"
  3. #include "Blueprint/UserWidget.h"
  4. #include "EnterChannelWidget.generated.h"
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9. };

在EnterChannelWidget.h文件中增加一些必要的 include:

  1. //EnterCahnnelWidget.h
  2. #include "CoreMinimal.h"
  3. #include "Blueprint/UserWidget.h"
  4. #include "Components/TextBlock.h"
  5. #include "Components/RichTextBlock.h"
  6. #include "Components/EditableTextBox.h"
  7. #include "Components/ComboBoxString.h"
  8. #include "Components/Button.h"
  9. #include "Components/Image.h"
  10. #include "VideoCall.h"
  11. #include "EnterChannelWidget.generated.h"
  1. class AVideoCallPlayerController;
  2. //EnterCahnnelWidget.cpp
  3. #include "Blueprint/WidgetTree.h"
  4. #include "VideoCallPlayerController.h"

然后我们需要增加如下变量:

  1. //EnterChannelWidget.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  5. {
  6. GENERATED_BODY()
  7. public:
  8. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  9. UTextBlock* HeaderTextBlock = nullptr;
  10. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  11. UTextBlock* DescriptionTextBlock = nullptr;
  12. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  13. UEditableTextBox* ChannelNameTextBox = nullptr;
  14. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  15. UEditableTextBox* EncriptionKeyTextBox = nullptr;
  16. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  17. UTextBlock* EncriptionTypeTextBlock = nullptr;
  18. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  19. UComboBoxString* EncriptionTypeComboBox = nullptr;
  20. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  21. UButton* JoinButton = nullptr;
  22. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  23. UButton* TestButton = nullptr;
  24. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  25. UButton* VideoSettingsButton = nullptr;
  26. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  27. UTextBlock* ContactsTextBlock = nullptr;
  28. UPROPERTY(VisibleAnywhere, BlueprintReadOnly, meta = (BindWidget))
  29. UTextBlock* BuildInfoTextBlock = nullptr;
  30. ...
  31. };

这些变量用来公职 blueprint asset 中相关的 UI 元素。这里最重要的是 BindWidget 元属性。通过将指向小部件的指针标记为 BindWidget,你可以在你的 C++类的 Blueprint 子类中创建一个同名的小部件,并在运行时从 C++中访问它。

同时,还要添加如下成员:

  1. //EnterChannelWidget.h
  2. ...
  3. UCLASS()
  4. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  5. {
  6. GENERATED_BODY()
  7. ...
  8. public:
  9. AVideoCallPlayerController* PlayerController = nullptr;
  10. TUniquePtr<VideoCall> VideoCallPtr;
  11. ...
  12. };

添加 Constructor 和 Construct/Destruct 方法

  1. //EnterChannelWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. UEnterChannelWidget(const FObjectInitializer& objectInitializer);
  15.  
  16. void NativeConstruct() override;
  17.  
  18. ...
  19. };
  20. //EnterChannelWidget.cpp
  21.  
  22. UEnterChannelWidget::UEnterChannelWidget(const FObjectInitializer& objectInitializer)
  23. : Super(objectInitializer)
  24. {
  25. }
  26.  
  27. void UEnterChannelWidget::NativeConstruct()
  28. {
  29. Super::NativeConstruct();
  30.  
  31. if (HeaderTextBlock)
  32. HeaderTextBlock->SetText(FText::FromString("Enter a conference room name"));
  33.  
  34. if (DescriptionTextBlock)
  35. DescriptionTextBlock->SetText(FText::FromString("If you are the first person to specify this name, \
  36. the room will be created and you will\nbe placed in it. \
  37. If it has already been created you will join the conference in progress"));
  38.  
  39. if (ChannelNameTextBox)
  40. ChannelNameTextBox->SetHintText(FText::FromString("Channel Name"));
  41.  
  42. if (EncriptionKeyTextBox)
  43. EncriptionKeyTextBox->SetHintText(FText::FromString("Encription Key"));
  44.  
  45. if (EncriptionTypeTextBlock)
  46. EncriptionTypeTextBlock->SetText(FText::FromString("Enc Type:"));
  47.  
  48. if (EncriptionTypeComboBox)
  49. {
  50. EncriptionTypeComboBox->AddOption("aes-128");
  51. EncriptionTypeComboBox->AddOption("aes-256");
  52. EncriptionTypeComboBox->SetSelectedIndex(0);
  53. }
  54.  
  55. if (JoinButton)
  56. {
  57. UTextBlock* JoinTextBlock = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
  58. JoinTextBlock->SetText(FText::FromString("Join"));
  59. JoinButton->AddChild(JoinTextBlock);
  60. JoinButton->OnClicked.AddDynamic(this, &UEnterChannelWidget::OnJoin);
  61. }
  62.  
  63. if (ContactsTextBlock)
  64. ContactsTextBlock->SetText(FText::FromString("agora.io Contact support: 400 632 6626"));
  65.  
  66. if (BuildInfoTextBlock)
  67. BuildInfoTextBlock->SetText(FText::FromString(" "));
  68. }

增加 Setter 方法

初始化 PlayerController 和 VideoCallPtr 变量

  1. //EnterChannelWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. void SetVideoCallPlayerController(AVideoCallPlayerController* VideoCallPlayerController);
  15.  
  16. void SetVideoCall(TUniquePtr<VideoCall> PassedVideoCallPtr);
  17.  
  18. ...
  19. };
  20. //EnterChannelWidget.cpp
  21.  
  22. void UEnterChannelWidget::SetVideoCallPlayerController(AVideoCallPlayerController* VideoCallPlayerController)
  23. {
  24. PlayerController = VideoCallPlayerController;
  25. }
  26.  
  27. void UEnterChannelWidget::SetVideoCall(TUniquePtr<VideoCall> PassedVideoCallPtr)
  28. {
  29. VideoCallPtr = std::move(PassedVideoCallPtr);
  30. }

增加 BlueprintCallable方法

要对相应的按钮 "onButtonClick "事件做出反应。

  1. //EnterChannelWidget.h
  2. ..
  3.  
  4. UCLASS()
  5. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  6. {
  7. GENERATED_BODY()
  8.  
  9. public:
  10.  
  11. ...
  12.  
  13. UFUNCTION(BlueprintCallable)
  14. void OnJoin();
  15.  
  16. ...
  17. };
  18. //EnterChannelWidget.cpp
  19.  
  20. void UEnterChannelWidget::OnJoin()
  21. {
  22. if (!PlayerController || !VideoCallPtr)
  23. {
  24. return;
  25. }
  26.  
  27. FString ChannelName = ChannelNameTextBox->GetText().ToString();
  28.  
  29. FString EncryptionKey = EncriptionKeyTextBox->GetText().ToString();
  30. FString EncryptionType = EncriptionTypeComboBox->GetSelectedOption();
  31.  
  32. SetVisibility(ESlateVisibility::Collapsed);
  33.  
  34. PlayerController->StartCall(
  35. std::move(VideoCallPtr),
  36. ChannelName,
  37. EncryptionKey,
  38. EncryptionType);
  39. }

增加 update 方法

  1. //EnterChannelWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UEnterChannelWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11. ...
  12.  
  13. void UpdateVersionText(FString newValue);
  14.  
  15. ...
  16. };
  17. //EnterChannelWidget.cpp
  18.  
  19. void UEnterChannelWidget::UpdateVersionText(FString newValue)
  20. {
  21. if (BuildInfoTextBlock)
  22. BuildInfoTextBlock->SetText(FText::FromString(newValue));
  23. }

创建 VideoViewWidget C++ 类

VideoViewWidget是一个存储动态纹理并使用RGBA buffer 更新动态纹理的类,该类是从VideoCall OnLocalFrameCallback/OnRemoteFrameCallback函数中接收到的。

创建类和添加所需的 include

  1. //VideoViewWidget.h
  2.  
  3. #include "CoreMinimal.h"
  4. #include "Blueprint/UserWidget.h"
  5.  
  6. #include "Components/Image.h"
  7.  
  8. #include "VideoViewWidget.generated.h"
  9. //VideoViewWidget.cpp
  10.  
  11. #include "EngineUtils.h"
  12. #include "Engine/Texture2D.h"
  13.  
  14. #include <algorithm>

添加成员变量

  • Buffer:用于存储RGBA缓冲区、Width、Height和BufferSize的变量 - 视频帧的参数。
  • RenderTargetImage:允许你在UI中显示Slate Brush或纹理或材质的图像小部件。
  • RenderTargetTexture:动态纹理,我们将使用Buffer变量更新。

FUpdateTextureRegion2D:指定一个纹理的更新区域 刷子 - 一个包含如何绘制Slate元素的笔刷。我们将用它来绘制RenderTargetImage上的RenderTargetTexture。

  1. //VideoViewWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoViewWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  12. UImage* RenderTargetImage = nullptr;
  13.  
  14. UPROPERTY(EditDefaultsOnly)
  15. UTexture2D* RenderTargetTexture = nullptr;
  16.  
  17. UTexture2D* CameraoffTexture = nullptr;
  18.  
  19. uint8* Buffer = nullptr;
  20. uint32_t Width = 0;
  21. uint32_t Height = 0;
  22. uint32 BufferSize = 0;
  23. FUpdateTextureRegion2D* UpdateTextureRegion = nullptr;
  24.  
  25. FSlateBrush Brush;
  26.  
  27. FCriticalSection Mutex;
  28.  
  29. ...
  30. };

覆盖 NativeConstruct() 方法

在NativeConstruct中,我们将用默认颜色初始化我们的图像。为了初始化我们的RenderTargetTexture,我们需要使用CreateTransient调用创建动态纹理(Texture2D)。然后分配BufferSize为Width * Height * 4的BufferSize(用于存储RGBA格式,每个像素可以用4个字节表示)。为了更新我们的纹理,我们可以使用UpdateTextureRegions函数。这个函数的输入参数之一是我们的像素数据缓冲区。这样,每当我们修改像素数据缓冲区时,我们就需要调用这个函数来使变化在纹理中可见。现在用我们的RenderTargetTexture初始化Brush变量,然后在RenderTargetImage widget中设置这个Brush。

  1. //VideoViewWidget.h
  2. ...
  3.  
  4. UCLASS()
  5. class AGORAVIDEOCALL_API UVideoViewWidget : public UUserWidget
  6. {
  7. GENERATED_BODY()
  8.  
  9. public:
  10.  
  11. ...
  12.  
  13. void NativeConstruct() override;
  14.  
  15. ...
  16. };
  17. //VideoViewWidget.cpp
  18.  
  19. void UVideoViewWidget::NativeConstruct()
  20. {
  21. Super::NativeConstruct();
  22.  
  23. Width = 640;
  24. Height = 360;
  25.  
  26. RenderTargetTexture = UTexture2D::CreateTransient(Width, Height, PF_R8G8B8A8);
  27. RenderTargetTexture->UpdateResource();
  28.  
  29. BufferSize = Width * Height * 4;
  30. Buffer = new uint8[BufferSize];
  31. for (uint32 i = 0; i < Width * Height; ++i)
  32. {
  33. Buffer[i * 4 + 0] = 0x32;
  34. Buffer[i * 4 + 1] = 0x32;
  35. Buffer[i * 4 + 2] = 0x32;
  36. Buffer[i * 4 + 3] = 0xFF;
  37. }
  38. UpdateTextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);
  39. RenderTargetTexture->UpdateTextureRegions(0, 1, UpdateTextureRegion, Width * 4, (uint32)4, Buffer);
  40.  
  41. Brush.SetResourceObject(RenderTargetTexture);
  42. RenderTargetImage->SetBrush(Brush);
  43. }

覆盖 NativeDestruct() 方法

  1. //VideoViewWidget.h
  2. ...
  3.  
  4. UCLASS()
  5. class AGORAVIDEOCALL_API UVideoViewWidget : public UUserWidget
  6. {
  7. GENERATED_BODY()
  8.  
  9. public:
  10.  
  11. ...
  12.  
  13. void NativeDestruct() override;
  14.  
  15. ...
  16. };
  17. //VideoViewWidget.cpp
  18.  
  19. void UVideoViewWidget::NativeDestruct()
  20. {
  21. Super::NativeDestruct();
  22.  
  23. delete[] Buffer;
  24. delete UpdateTextureRegion;
  25. }

覆盖 NativeTick() 方法

如果UpdateTextureRegion Width或Height不等于memember的Width Height值,我们需要重新创建RenderTargetTexture以支持更新的值,并像Native Construct成员一样重复初始化。否则只需用Buffer调用UpdateTextureRegions。

  1. //VideoViewWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoViewWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. void NativeTick(const FGeometry& MyGeometry, float DeltaTime) override;
  15.  
  16. ...
  17. };
  18. //VideoViewWidget.cpp
  19.  
  20. void UVideoViewWidget::NativeTick(const FGeometry& MyGeometry, float DeltaTime)
  21. {
  22. Super::NativeTick(MyGeometry, DeltaTime);
  23.  
  24. FScopeLock lock(&Mutex);
  25.  
  26. if (UpdateTextureRegion->Width != Width ||
  27. UpdateTextureRegion->Height != Height)
  28. {
  29. auto NewUpdateTextureRegion = new FUpdateTextureRegion2D(0, 0, 0, 0, Width, Height);
  30.  
  31. auto NewRenderTargetTexture = UTexture2D::CreateTransient(Width, Height, PF_R8G8B8A8);
  32. NewRenderTargetTexture->UpdateResource();
  33. NewRenderTargetTexture->UpdateTextureRegions(0, 1, NewUpdateTextureRegion, Width * 4, (uint32)4, Buffer);
  34.  
  35. Brush.SetResourceObject(NewRenderTargetTexture);
  36. RenderTargetImage->SetBrush(Brush);
  37.  
  38. //UClass's such as UTexture2D are automatically garbage collected when there is no hard pointer references made to that object.
  39. //So if you just leave it and don't reference it elsewhere then it will be destroyed automatically.
  40.  
  41. FUpdateTextureRegion2D* TmpUpdateTextureRegion = UpdateTextureRegion;
  42.  
  43. RenderTargetTexture = NewRenderTargetTexture;
  44. UpdateTextureRegion = NewUpdateTextureRegion;
  45.  
  46. delete TmpUpdateTextureRegion;
  47. return;
  48. }
  49. RenderTargetTexture->UpdateTextureRegions(0, 1, UpdateTextureRegion, Width * 4, (uint32)4, Buffer);
  50. }

增加 UpdateBuffer() 方法

通过调用来更新 Buffer 值。我们希望从 Agora SDK 线程接收到新的值。由于 UE4 的限制,我们将值保存到变量 Buffer 中,并在 NativeTick 方法中更新纹理,所以这里不调用UpdateTextureRegions。

  1. //VideoViewWidget.h
  2. ...
  3.  
  4. UCLASS()
  5. class AGORAVIDEOCALL_API UVideoViewWidget : public UUserWidget
  6. {
  7. GENERATED_BODY()
  8.  
  9. public:
  10.  
  11. ...
  12.  
  13. void UpdateBuffer( uint8* RGBBuffer, uint32_t Width, uint32_t Height, uint32_t Size );
  14. void ResetBuffer();
  15. ...
  16. };
  17. //VideoViewWidget.cpp
  18.  
  19. void UVideoViewWidget::UpdateBuffer(
  20. uint8* RGBBuffer,
  21. uint32_t NewWidth,
  22. uint32_t NewHeight,
  23. uint32_t NewSize)
  24. {
  25. FScopeLock lock(&Mutex);
  26.  
  27. if (!RGBBuffer)
  28. {
  29. return;
  30. }
  31.  
  32. if (BufferSize == NewSize)
  33. {
  34. std::copy(RGBBuffer, RGBBuffer + NewSize, Buffer);
  35. }
  36. else
  37. {
  38. delete[] Buffer;
  39. BufferSize = NewSize;
  40. Width = NewWidth;
  41. Height = NewHeight;
  42. Buffer = new uint8[BufferSize];
  43. std::copy(RGBBuffer, RGBBuffer + NewSize, Buffer);
  44. }
  45. }
  46.  
  47. void UVideoViewWidget::ResetBuffer()
  48. {
  49. for (uint32 i = 0; i < Width * Height; ++i)
  50. {
  51. Buffer[i * 4 + 0] = 0x32;
  52. Buffer[i * 4 + 1] = 0x32;
  53. Buffer[i * 4 + 2] = 0x32;
  54. Buffer[i * 4 + 3] = 0xFF;
  55. }
  56. }

创建 VideoCallViewWidget C++类

VideoCallViewWidget 类的作用是显示本地和远程用户的视频。我们需要两个 VideoViewWidget 小部件,一个用来显示来自本地摄像头的视频,另一个用来显示从远程用户收到的视频(假设我们只支持一个远程用户)。

创建类和添加所需的 include

像之前那样创建Widget C++类,添加所需的include。

  1. //VideoCallViewWidget.h
  2.  
  3. #include "CoreMinimal.h"
  4. #include "Blueprint/UserWidget.h"
  5. #include "Components/SizeBox.h"
  6.  
  7. #include "VideoViewWidget.h"
  8.  
  9. #include "VideoCallViewWidget.generated.h"
  10. //VideoCallViewWidget.cpp
  11.  
  12. #include "Components/CanvasPanelSlot.h"

添加成员变量

  1. //VideoCallViewWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallViewWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  13. UVideoViewWidget* MainVideoViewWidget = nullptr;
  14.  
  15. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  16. USizeBox* MainVideoSizeBox = nullptr;
  17.  
  18. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  19. UVideoViewWidget* AdditionalVideoViewWidget = nullptr;
  20.  
  21. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  22. USizeBox* AdditionalVideoSizeBox = nullptr;
  23.  
  24. public:
  25. int32 MainVideoWidth = 0;
  26. int32 MainVideoHeight = 0;
  27.  
  28. ...
  29. };

覆盖 NativeTick() 方法

  1. ``
  2. //VideoCallViewWidget.h
  3.  
  4. ...
  5.  
  6. UCLASS()
  7. class AGORAVIDEOCALL_API UVideoCallViewWidget : public UUserWidget
  8. {
  9. GENERATED_BODY()
  10.  
  11. public:
  12.  
  13. ...
  14.  
  15. void NativeTick(const FGeometry& MyGeometry, float DeltaTime) override;
  16.  
  17. ...
  18. };
  19. //VideoCallViewWidget.cpp
  20.  
  21. void UVideoCallViewWidget::NativeTick(const FGeometry& MyGeometry, float DeltaTime)
  22. {
  23. Super::NativeTick(MyGeometry, DeltaTime);
  24.  
  25. auto ScreenSize = MyGeometry.GetLocalSize();
  26.  
  27. if (MainVideoHeight != 0)
  28. {
  29. float AspectRatio = 0;
  30. AspectRatio = MainVideoWidth / (float)MainVideoHeight;
  31.  
  32. auto MainVideoGeometry = MainVideoViewWidget->GetCachedGeometry();
  33. auto MainVideoScreenSize = MainVideoGeometry.GetLocalSize();
  34. if (MainVideoScreenSize.X == 0)
  35. {
  36. return;
  37. }
  38.  
  39. auto NewMainVideoHeight = MainVideoScreenSize.Y;
  40. auto NewMainVideoWidth = AspectRatio * NewMainVideoHeight;
  41.  
  42. MainVideoSizeBox->SetMinDesiredWidth(NewMainVideoWidth);
  43. MainVideoSizeBox->SetMinDesiredHeight(NewMainVideoHeight);
  44.  
  45. UCanvasPanelSlot* CanvasSlot = Cast<UCanvasPanelSlot>(MainVideoSizeBox->Slot);
  46. CanvasSlot->SetAutoSize(true);
  47.  
  48. FVector2D NewPosition;
  49. NewPosition.X = -NewMainVideoWidth / 2;
  50. NewPosition.Y = -NewMainVideoHeight / 2;
  51. CanvasSlot->SetPosition(NewPosition);
  52. }
  53. }

更新 UpdateMainVideoBuffer/UpdateAdditionalVideoBuffe

  1. //VideoCallViewWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallViewWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. void UpdateMainVideoBuffer( uint8* RGBBuffer, uint32_t Width, uint32_t Height, uint32_t Size);
  15. void UpdateAdditionalVideoBuffer( uint8* RGBBuffer, uint32_t Width, uint32_t Height, uint32_t Size);
  16.  
  17. void ResetBuffers();
  18. ...
  19. };
  20. //VideoCallViewWidget.cpp
  21.  
  22. void UVideoCallViewWidget::UpdateMainVideoBuffer(
  23. uint8* RGBBuffer,
  24. uint32_t Width,
  25. uint32_t Height,
  26. uint32_t Size)
  27. {
  28. if (!MainVideoViewWidget)
  29. {
  30. return;
  31. }
  32. MainVideoWidth = Width;
  33. MainVideoHeight = Height;
  34. MainVideoViewWidget->UpdateBuffer(RGBBuffer, Width, Height, Size);
  35. }
  36.  
  37. void UVideoCallViewWidget::UpdateAdditionalVideoBuffer(
  38. uint8* RGBBuffer,
  39. uint32_t Width,
  40. uint32_t Height,
  41. uint32_t Size)
  42. {
  43. if (!AdditionalVideoViewWidget)
  44. {
  45. return;
  46. }
  47. AdditionalVideoViewWidget->UpdateBuffer(RGBBuffer, Width, Height, Size);
  48. }
  49.  
  50. void UVideoCallViewWidget::ResetBuffers()
  51. {
  52. if (!MainVideoViewWidget || !AdditionalVideoViewWidget)
  53. {
  54. return;
  55. }
  56. MainVideoViewWidget->ResetBuffer();
  57. AdditionalVideoViewWidget->ResetBuffer();
  58. }

创建 VideoCallWidget C++ 类

VideoCallWidget 类作为示例应用程序的音频/视频调用小部件。它包含以下控件,与蓝图资产中的UI元素绑定。

创建类和添加所需的include

像之前那样创建Widget C++类,添加必要的include和转发声明。

  1. //VideoCallWidget.h
  2. #include "CoreMinimal.h"
  3. #include "Blueprint/UserWidget.h"
  4.  
  5. #include "Templates/UniquePtr.h"
  6. #include "Components/Image.h"
  7. #include "Components/Button.h"
  8. #include "Engine/Texture2D.h"
  9.  
  10. #include "VideoCall.h"
  11.  
  12. #include "VideoCallViewWidget.h"
  13.  
  14. #include "VideoCallWidget.generated.h"
  15.  
  16. class AVideoCallPlayerController;
  17. class UVideoViewWidget;
  18. //VideoCallWidget.cpp
  19.  
  20. #include "Kismet/GameplayStatics.h"
  21. #include "UObject/ConstructorHelpers.h"
  22. #include "Components/CanvasPanelSlot.h"
  23.  
  24. #include "VideoViewWidget.h"
  25.  
  26. #include "VideoCallPlayerController.h"

增加成员变量

  1. //VideoCallWidget.h
  2. ...
  3.  
  4. UCLASS()
  5. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  6. {
  7. GENERATED_BODY()
  8.  
  9. public:
  10. AVideoCallPlayerController* PlayerController = nullptr;
  11.  
  12. public:
  13. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  14. UVideoCallViewWidget* VideoCallViewWidget = nullptr;
  15.  
  16. //Buttons
  17. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  18. UButton* EndCallButton = nullptr;
  19. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  20. UButton* MuteLocalAudioButton = nullptr;
  21. UPROPERTY(BlueprintReadOnly, meta = (BindWidget))
  22. UButton* VideoModeButton = nullptr;
  23.  
  24. //Button textures
  25. int32 ButtonSizeX = 96;
  26. int32 ButtonSizeY = 96;
  27. UTexture2D* EndCallButtonTexture = nullptr;
  28. UTexture2D* AudioButtonMuteTexture = nullptr;
  29. UTexture2D* AudioButtonUnmuteTexture = nullptr;
  30. UTexture2D* VideomodeButtonCameraoffTexture = nullptr;
  31. UTexture2D* VideomodeButtonCameraonTexture = nullptr;
  32.  
  33. TUniquePtr<VideoCall> VideoCallPtr;
  34.  
  35. ...
  36. };

初始化VideoCallWidget

为每个按钮找到asset图像,并将其分配到相应的纹理。然后用纹理初始化每个按钮。

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ..
  13.  
  14. UVideoCallWidget(const FObjectInitializer& ObjectInitializer);
  15.  
  16. void NativeConstruct() override;
  17. void NativeDestruct() override;
  18.  
  19. private:
  20. void InitButtons();
  21.  
  22. ...
  23. };
  24. //VideoCallWidget.cpp
  25.  
  26. void UVideoCallWidget::NativeConstruct()
  27. {
  28. Super::NativeConstruct();
  29.  
  30. InitButtons();
  31. }
  32.  
  33. void UVideoCallWidget::NativeDestruct()
  34. {
  35. Super::NativeDestruct();
  36.  
  37. if (VideoCallPtr)
  38. {
  39. VideoCallPtr->StopCall();
  40. }
  41. }
  42.  
  43. UVideoCallWidget::UVideoCallWidget(const FObjectInitializer& ObjectInitializer)
  44. : Super(ObjectInitializer)
  45. {
  46. static ConstructorHelpers::FObjectFinder<UTexture2D>
  47. EndCallButtonTextureFinder(TEXT("Texture'/Game/ButtonTextures/hangup.hangup'"));
  48. if (EndCallButtonTextureFinder.Succeeded())
  49. {
  50. EndCallButtonTexture = EndCallButtonTextureFinder.Object;
  51. }
  52. static ConstructorHelpers::FObjectFinder<UTexture2D>
  53. AudioButtonMuteTextureFinder(TEXT("Texture'/Game/ButtonTextures/mute.mute'"));
  54. if (AudioButtonMuteTextureFinder.Succeeded())
  55. {
  56. AudioButtonMuteTexture = AudioButtonMuteTextureFinder.Object;
  57. }
  58. static ConstructorHelpers::FObjectFinder<UTexture2D>
  59. AudioButtonUnmuteTextureFinder(TEXT("Texture'/Game/ButtonTextures/unmute.unmute'"));
  60. if (AudioButtonUnmuteTextureFinder.Succeeded())
  61. {
  62. AudioButtonUnmuteTexture = AudioButtonUnmuteTextureFinder.Object;
  63. }
  64. static ConstructorHelpers::FObjectFinder<UTexture2D>
  65. VideomodeButtonCameraonTextureFinder(TEXT("Texture'/Game/ButtonTextures/cameraon.cameraon'"));
  66. if (VideomodeButtonCameraonTextureFinder.Succeeded())
  67. {
  68. VideomodeButtonCameraonTexture = VideomodeButtonCameraonTextureFinder.Object;
  69. }
  70. static ConstructorHelpers::FObjectFinder<UTexture2D>
  71. VideomodeButtonCameraoffTextureFinder(TEXT("Texture'/Game/ButtonTextures/cameraoff.cameraoff'"));
  72. if (VideomodeButtonCameraoffTextureFinder.Succeeded())
  73. {
  74. VideomodeButtonCameraoffTexture = VideomodeButtonCameraoffTextureFinder.Object;
  75. }
  76. }
  77.  
  78. void UVideoCallWidget::InitButtons()
  79. {
  80. if (EndCallButtonTexture)
  81. {
  82. EndCallButton->WidgetStyle.Normal.SetResourceObject(EndCallButtonTexture);
  83. EndCallButton->WidgetStyle.Normal.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  84. EndCallButton->WidgetStyle.Normal.DrawAs = ESlateBrushDrawType::Type::Image;
  85.  
  86. EndCallButton->WidgetStyle.Hovered.SetResourceObject(EndCallButtonTexture);
  87. EndCallButton->WidgetStyle.Hovered.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  88. EndCallButton->WidgetStyle.Hovered.DrawAs = ESlateBrushDrawType::Type::Image;
  89.  
  90. EndCallButton->WidgetStyle.Pressed.SetResourceObject(EndCallButtonTexture);
  91. EndCallButton->WidgetStyle.Pressed.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  92. EndCallButton->WidgetStyle.Pressed.DrawAs = ESlateBrushDrawType::Type::Image;
  93. }
  94. EndCallButton->OnClicked.AddDynamic(this, &UVideoCallWidget::OnEndCall);
  95.  
  96. SetAudioButtonToMute();
  97. MuteLocalAudioButton->OnClicked.AddDynamic(this, &UVideoCallWidget::OnMuteLocalAudio);
  98.  
  99. SetVideoModeButtonToCameraOff();
  100. VideoModeButton->OnClicked.AddDynamic(this, &UVideoCallWidget::OnChangeVideoMode);
  101.  
  102. }

添加按钮纹理

在演示程序中找到目录Content/ButtonTextures(你不必打开项目,只需在文件系统中找到这个文件夹即可)。所有的按钮纹理都存储在那里。在你的项目内容中创建一个名为ButtonTextures的新目录,将所有的按钮图片拖放到那里,让它们在你的项目中可用。

添加Setters

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. ...
  11.  
  12. public:
  13. void SetVideoCallPlayerController(AVideoCallPlayerController* VideoCallPlayerController);
  14. void SetVideoCall(TUniquePtr<VideoCall> PassedVideoCallPtr);
  15.  
  16. ...
  17. };
  18. //VideoCallWidget.cpp
  19.  
  20. void UVideoCallWidget::SetVideoCallPlayerController(AVideoCallPlayerController* VideoCallPlayerController)
  21. {
  22. PlayerController = VideoCallPlayerController;
  23. }
  24.  
  25. void UVideoCallWidget::SetVideoCall(TUniquePtr<VideoCall> PassedVideoCallPtr)
  26. {
  27. VideoCallPtr = std::move(PassedVideoCallPtr);
  28. }

增加用来更新 view 的方法

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. ...
  11.  
  12. private:
  13.  
  14. void SetVideoModeButtonToCameraOff();
  15. void SetVideoModeButtonToCameraOn();
  16.  
  17. void SetAudioButtonToMute();
  18. void SetAudioButtonToUnMute();
  19.  
  20. ...
  21. };
  22. //VideoCallWidget.cpp
  23.  
  24. void UVideoCallWidget::SetVideoModeButtonToCameraOff()
  25. {
  26. if (VideomodeButtonCameraoffTexture)
  27. {
  28. VideoModeButton->WidgetStyle.Normal.SetResourceObject(VideomodeButtonCameraoffTexture);
  29. VideoModeButton->WidgetStyle.Normal.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  30. VideoModeButton->WidgetStyle.Normal.DrawAs = ESlateBrushDrawType::Type::Image;
  31.  
  32. VideoModeButton->WidgetStyle.Hovered.SetResourceObject(VideomodeButtonCameraoffTexture);
  33. VideoModeButton->WidgetStyle.Hovered.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  34. VideoModeButton->WidgetStyle.Hovered.DrawAs = ESlateBrushDrawType::Type::Image;
  35.  
  36. VideoModeButton->WidgetStyle.Pressed.SetResourceObject(VideomodeButtonCameraoffTexture);
  37. VideoModeButton->WidgetStyle.Pressed.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  38. VideoModeButton->WidgetStyle.Pressed.DrawAs = ESlateBrushDrawType::Type::Image;
  39. }
  40. }
  41.  
  42. void UVideoCallWidget::SetVideoModeButtonToCameraOn()
  43. {
  44. if (VideomodeButtonCameraonTexture)
  45. {
  46. VideoModeButton->WidgetStyle.Normal.SetResourceObject(VideomodeButtonCameraonTexture);
  47. VideoModeButton->WidgetStyle.Normal.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  48. VideoModeButton->WidgetStyle.Normal.DrawAs = ESlateBrushDrawType::Type::Image;
  49.  
  50. VideoModeButton->WidgetStyle.Hovered.SetResourceObject(VideomodeButtonCameraonTexture);
  51. VideoModeButton->WidgetStyle.Hovered.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  52. VideoModeButton->WidgetStyle.Hovered.DrawAs = ESlateBrushDrawType::Type::Image;
  53.  
  54. VideoModeButton->WidgetStyle.Pressed.SetResourceObject(VideomodeButtonCameraonTexture);
  55. VideoModeButton->WidgetStyle.Pressed.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  56. VideoModeButton->WidgetStyle.Pressed.DrawAs = ESlateBrushDrawType::Type::Image;
  57. }
  58. }
  59.  
  60. void UVideoCallWidget::SetAudioButtonToMute()
  61. {
  62. if (AudioButtonMuteTexture)
  63. {
  64. MuteLocalAudioButton->WidgetStyle.Normal.SetResourceObject(AudioButtonMuteTexture);
  65. MuteLocalAudioButton->WidgetStyle.Normal.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  66. MuteLocalAudioButton->WidgetStyle.Normal.DrawAs = ESlateBrushDrawType::Type::Image;
  67.  
  68. MuteLocalAudioButton->WidgetStyle.Hovered.SetResourceObject(AudioButtonMuteTexture);
  69. MuteLocalAudioButton->WidgetStyle.Hovered.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  70. MuteLocalAudioButton->WidgetStyle.Hovered.DrawAs = ESlateBrushDrawType::Type::Image;
  71.  
  72. MuteLocalAudioButton->WidgetStyle.Pressed.SetResourceObject(AudioButtonMuteTexture);
  73. MuteLocalAudioButton->WidgetStyle.Pressed.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  74. MuteLocalAudioButton->WidgetStyle.Pressed.DrawAs = ESlateBrushDrawType::Type::Image;
  75. }
  76. }
  77.  
  78. void UVideoCallWidget::SetAudioButtonToUnMute()
  79. {
  80. if (AudioButtonUnmuteTexture)
  81. {
  82. MuteLocalAudioButton->WidgetStyle.Normal.SetResourceObject(AudioButtonUnmuteTexture);
  83. MuteLocalAudioButton->WidgetStyle.Normal.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  84. MuteLocalAudioButton->WidgetStyle.Normal.DrawAs = ESlateBrushDrawType::Type::Image;
  85.  
  86. MuteLocalAudioButton->WidgetStyle.Hovered.SetResourceObject(AudioButtonUnmuteTexture);
  87. MuteLocalAudioButton->WidgetStyle.Hovered.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  88. MuteLocalAudioButton->WidgetStyle.Hovered.DrawAs = ESlateBrushDrawType::Type::Image;
  89.  
  90. MuteLocalAudioButton->WidgetStyle.Pressed.SetResourceObject(AudioButtonUnmuteTexture);
  91. MuteLocalAudioButton->WidgetStyle.Pressed.ImageSize = FVector2D(ButtonSizeX, ButtonSizeY);
  92. MuteLocalAudioButton->WidgetStyle.Pressed.DrawAs = ESlateBrushDrawType::Type::Image;
  93. }
  94. }

增加 OnStartCall 方法

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. void OnStartCall( const FString& ChannelName, const FString& EncryptionKey, const FString& EncryptionType );
  15.  
  16. ...
  17. };
  18. //VideoCallWidget.cpp
  19.  
  20. void UVideoCallWidget::OnStartCall(
  21. const FString& ChannelName,
  22. const FString& EncryptionKey,
  23. const FString& EncryptionType)
  24. {
  25. if (!VideoCallPtr)
  26. {
  27. return;
  28. }
  29.  
  30. auto OnLocalFrameCallback = [this](
  31. std::uint8_t* Buffer,
  32. std::uint32_t Width,
  33. std::uint32_t Height,
  34. std::uint32_t Size)
  35. {
  36. VideoCallViewWidget->UpdateAdditionalVideoBuffer(Buffer, Width, Height, Size);
  37. };
  38. VideoCallPtr->RegisterOnLocalFrameCallback(OnLocalFrameCallback);
  39.  
  40. auto OnRemoteFrameCallback = [this](
  41. std::uint8_t* Buffer,
  42. std::uint32_t Width,
  43. std::uint32_t Height,
  44. std::uint32_t Size)
  45. {
  46. VideoCallViewWidget->UpdateMainVideoBuffer(Buffer, Width, Height, Size);
  47. };
  48. VideoCallPtr->RegisterOnRemoteFrameCallback(OnRemoteFrameCallback);
  49.  
  50. VideoCallPtr->StartCall(ChannelName, EncryptionKey, EncryptionType);
  51. }

增加 OnEndCall方法

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. UFUNCTION(BlueprintCallable)
  15. void OnEndCall();
  16.  
  17. ...
  18. };
  19. //VideoCallWidget.cpp
  20.  
  21. void UVideoCallWidget::OnEndCall()
  22. {
  23. if (VideoCallPtr)
  24. {
  25. VideoCallPtr->StopCall();
  26. }
  27.  
  28. if (VideoCallViewWidget)
  29. {
  30. VideoCallViewWidget->ResetBuffers();
  31. }
  32.  
  33. if (PlayerController)
  34. {
  35. SetVisibility(ESlateVisibility::Collapsed);
  36. PlayerController->EndCall(std::move(VideoCallPtr));
  37. }
  38. }

增加 OnMuteLocalAudio 方法

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. UFUNCTION(BlueprintCallable)
  15. void OnMuteLocalAudio();
  16.  
  17. ...
  18. };
  19. //VideoCallWidget.cpp
  20.  
  21. void UVideoCallWidget::OnMuteLocalAudio()
  22. {
  23. if (!VideoCallPtr)
  24. {
  25. return;
  26. }
  27. if (VideoCallPtr->IsLocalAudioMuted())
  28. {
  29. VideoCallPtr->MuteLocalAudio(false);
  30. SetAudioButtonToMute();
  31. }
  32. else
  33. {
  34. VideoCallPtr->MuteLocalAudio(true);
  35. SetAudioButtonToUnMute();
  36. }
  37. }

增加 OnChangeVideoMode方法

  1. //VideoCallWidget.h
  2.  
  3. ...
  4.  
  5. UCLASS()
  6. class AGORAVIDEOCALL_API UVideoCallWidget : public UUserWidget
  7. {
  8. GENERATED_BODY()
  9.  
  10. public:
  11.  
  12. ...
  13.  
  14. UFUNCTION(BlueprintCallable)
  15. void OnChangeVideoMode();
  16.  
  17. ...
  18. };
  19. //VideoCallWidget.cpp
  20.  
  21. void UVideoCallWidget::OnChangeVideoMode()
  22. {
  23. if (!VideoCallPtr)
  24. {
  25. return;
  26. }
  27. if (!VideoCallPtr->IsLocalVideoMuted())
  28. {
  29. VideoCallPtr->MuteLocalVideo(true);
  30.  
  31. SetVideoModeButtonToCameraOn();
  32. }
  33. else
  34. {
  35. VideoCallPtr->EnableVideo(true);
  36. VideoCallPtr->MuteLocalVideo(false);
  37.  
  38. SetVideoModeButtonToCameraOff();
  39. }
  40. }

增加 Blueprint 类

确保C++代码正确编译。没有成功编译的项目,你将无法进行下一步的操作。如果你已经成功地编译了C++代码,但在虚幻编辑器中仍然没有看到所需的类,请尝试重新打开项目。

创建 BP_EnterChannelWidget Blueprint Asset。

创建一个 UEnterChannelWidget 的 Blueprint,右键点击内容,选择用户界面菜单并选择 Widget Blueprint。

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

更改这个新的用户小工具的类的父类。打开 Blueprint,会出现 UMG 编辑器界面,默认情况下 Designer 选项卡是打开的。点击图形按钮(右上角按钮),选择 "类设置"。在面板 "Details "中,点击下拉列表 "父类",选择之前创建的C++ 类 UEnterChannelWidget。现在返回到设计页面。调色板窗口包含几种不同类型的小部件,你可以用它们来构造你的 UI 元素。找到 Text、Editable Text、Button 和 ComboBox(String)元素,然后将它们拖到工作区,如图中所示。然后进入 "EnterChannelWidget.h "文件中的 UEnterChannelWidget 的定义,查看成员变量的名称和对应的类型(UTextBlock、EditableTextBox、UButton和UComboBoxString)。返回到 BP_VideoCallWiewVidget 编辑器中,给你拖动的UI元素设置相同的名称。你可以通过点击元素并在 "详细信息 "面板中更改名称来完成。尝试编译蓝图。如果你忘了添加什么东西,或者在你的UserWidget类中出现了widget名称/类型不匹配的情况,你会出现一个错误。

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

保存到文件夹中,例如 /Content/Widgets/BP_EnterChannelWidget.uasset。

创建 BP_VideoViewWidget Asset。

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

设定图片的锚点

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

创建 BP_VideoCallViewWidget Asset

创建 BP VideoCallViewWidget Asset ,将父类设置为 UVideoCallViewWidget,并添加 BP VideoViewWidget 类型的 UI 元素MainVideoViewWidget 和ExtendedVideoViewWidget。同时添加 SizeBox 类型的 MainVideoSizeBox 和 AdditionalVideoSizeBox UI 元素。

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

创建 BP_VideoCallWidget Asset

创建BPVideoCallWidget Asset,将父类设置为UVideoCallWidget,在 Palette UI 元素BPVideoCallViewWidget 中找到并添加名称为VideoCallViewWidget,添加 EndCallButton、MuteLocalAudioButton 和 VideoModeButton 按钮。

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

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

创建 BP_VideoCallPlayerController blueprint asset

现在是创建 BPVideoCallPlayerPlayerController blueprint asset 的时候了,基于我们前面描述的 AVideoCallPlayerPlayerController 类,创建 BPVideoCallPlayerController 蓝图资产。

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

创建一个AVideoCallPlayerPlayerController的bluepringt。右键点击内容,按Add New按钮,选择Blueprint类,在窗口中选择父类,在Pick parent类进入All classes部分,找到VideoCallPlayerController类。

现在将我们之前创建的小部件分配给PlayerController,如下图所示。

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

将其保存到文件夹,例如 /Content/Widgets/BP_VideoCallPlayerController.uasset。

创建 BP_AgoraVideoCallGameModeBase Asset

创建一个 AVideoCallPlayerController 的 Blueprint,右键点击内容,按 Add New 按钮,选择 Blueprint 类,在 Pick parent class 窗口中选择 Game Mode Base Class。这是所有游戏模式的父类。

修改 GameMode

现在你需要设置你的自定义 GameMode 类和玩家控制器。到世界设置中,设置指定的变量:

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

指定项目的设置

进入 Edit->Project settings,打开 Maps & Modes。设定默认参数:

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

总结

到此这篇关于C++ 在 Unreal 中为游戏增加实时音视频互动的文章就介绍到这了,更多相关C++ 游戏增加音视频互动内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/agora_cloud/article/details/106293719