可捕获声波
概述
可捕获声波派生自流式声波。它支持从麦克风等输入设备捕获音频数据并进行回放,具有与导入声波相同的功能(包括倒放、在SoundCue中使用等)。你甚至可以同时捕获和播放音频,没有任何限制。
关于语音活动检测(VAD),请参阅此页面。
在iOS和Android平台上,可捕获声波会在开始捕获时自动请求麦克风权限。
基础用法
创建可捕获声波
首先需要创建一个可捕获声波。
- 蓝图
- C++
UCapturableSoundWave* CapturableSoundWave = UCapturableSoundWave::CreateCapturableSoundWave();
应将可捕获的声波视为强引用以防止过早销毁(例如在蓝图中将其赋值给单独变量,或在C++中使用UPROPERTY()
)。
获取可用输入设备
要使用此功能,首先需要获取所有可用于捕获的音频输入设备。
- Blueprint
- C++
UCapturableSoundWave::GetAvailableAudioInputDevices(FOnGetAvailableAudioInputDevicesResultNative::CreateWeakLambda(this, [](const TArray<FRuntimeAudioInputDeviceInfo>& AvailableDevices)
{
// Handle the result
}));
开始与停止捕获
获取可用设备后,您可以开始从输入设备捕获音频数据,并在需要时停止捕获。
- Blueprint
- C++
// Assuming CapturableSoundWave is a UE reference to a UCapturableSoundWave object (or its derived type)
// Start capturing audio data from the input device with the specified device ID (0 in this case)
CapturableSoundWave->StartCapture(0);
// Stop capturing audio data
CapturableSoundWave->StopCapture();
DeviceId 是设备在可用设备数组中的索引,该数组通过上一步骤获取。
高级功能
静音与取消静音采集
您可以选择静音或取消静音声音采集,以防止音频数据堆积,同时不会中断采集过程。
- Blueprint
- C++
// Assuming CapturableSoundWave is a UE reference to a UCapturableSoundWave object (or its derived type)
CapturableSoundWave->ToggleMute(true);
当需要频繁切换捕获时,这种方法非常有用,因为通过StartCapture
开始录制可能会在引擎端造成轻微卡顿。您应该先启动捕获本身,然后再进行静音/取消静音操作。
如果您的目标是消除轻微冻结,可以考虑在冻结影响可忽略不计的时机启动捕获。例如,您可以在游戏加载画面期间启动捕获,随后立即将可捕获音波静音,然后在需要捕获音频数据时取消静音,从而避免任何卡顿。
完整示例
以下是使用可捕获音波的完整实现示例:
- 蓝图
- C++
这是一个基础代码示例,展示如何使用可捕获音波从输入设备(麦克风)捕获音频数据。
该示例使用了位于EXAMPLEMODULE
模块中UCaptureAudioClassExample
类内的CaptureAudioExample
函数。
要成功运行此示例,请确保将RuntimeAudioImporter
模块添加到**.Build.cs文件中的PublicDependencyModuleNames
或PrivateDependencyModuleNames
,同时也要添加到项目的.uproject**文件中。
// 示例代码保持不变
#pragma once
#include "CoreMinimal.h"
#include "UObject/Object.h"
#include "CaptureAudioClassExample.generated.h"
UCLASS(BlueprintType)
class EXAMPLEMODULE_API UCaptureAudioClassExample : public UObject
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable)
void CaptureAudioExample();
private:
// Please pay attention to making the StreamingSoundWave a hard reference, such as using UPROPERTY(), to prevent it from being prematurely garbage collected
UPROPERTY()
class UCapturableSoundWave* CapturableSoundWave;
};
#include "CaptureAudioClassExample.h"
#include "Sound/StreamingSoundWave.h"
void UCaptureAudioClassExample::CaptureAudioExample()
{
// Create a capturable sound wave
CapturableSoundWave = UCapturableSoundWave::CreateCapturableSoundWave();
// Capture audio data from the input device with the specified device ID (0 in this case)
CapturableSoundWave->StartCapture(0);
// Delay for 5 seconds, just for demonstration purposes
FTimerHandle TimerHandle;
GetWorld()->GetTimerManager().SetTimer(TimerHandle, [this]()
{
// Stop capturing audio data
CapturableSoundWave->StopCapture();
// Play the sound wave
UGameplayStatics::PlaySound2D(GetWorld(), CapturableSoundWave);
}, 5, false);
}