可捕获声波
有关语音活动检测 (VAD),请参考这个页面。
有一种可捕获的声波从流式声波派生而来。它支持从输入设备(如麦克风)捕获音频数据并进行回放,并且具备与导入声波相同的能力(包括倒回、在 SoundCues 中使用等)。您甚至可以在捕获和播放音频的同时进行,无任何限制。
在捕获开始时,它还会自动请求 iOS 和 Android 的麦克风权限。
首先,您需要创建一个可捕获声波。请注意,您应该将其视为强引用以防止过早销毁(例如,通过在 Blueprints 中将其分配给一个单独的变量或在 C++ 中使用 UPROPERTY()
)。
- Blueprint
- C++
UCapturableSoundWave* CapturableSoundWave = UCapturableSoundWave::CreateCapturableSoundWave();
要使用此功能,您需要首先通过调用相应的函数获取可用于捕获的所有可用音频输入设备。
- Blueprint
- C++
UCapturableSoundWave::GetAvailableAudioInputDevices(FOnGetAvailableAudioInputDevicesResultNative::CreateWeakLambda(this, [](const TArray<FRuntimeAudioInputDeviceInfo>& AvailableDevices)
{
// Handle the result
}));
之后,您可以开始从输入设备捕获音频数据,并在需要时停止。DeviceId 是从前一步获得的可用设备数组中的设备索引。
- 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();
此外,您可以选择静音或取消静音音频捕获,以防止在不中断捕获过程的情况下积累音频数据。这在频繁切换捕获时很有用,因为通过 StartCapture
开始录音可能会导致引擎端出现轻微的卡顿。您应首先启动捕获本身,然后再进行静音/取消静音操作。
如果您的目标是消除轻微的卡顿,可以考虑在卡顿可能微不足道的时间开始捕获。例如,您可以在游戏加载屏幕期间开始捕获,立即将可捕获的声波静音,然后在需要捕获音频数据时取消静音可捕获的声波,以避免任何卡顿。
- Blueprint
- C++
// Assuming CapturableSoundWave is a UE reference to a UCapturableSoundWave object (or its derived type)
CapturableSoundWave->ToggleMute(true);
最后,你的实现可能如下所示:
- Blueprint
- C++
这是一个用于使用可捕获声音波形从输入设备(麦克风)捕捉音频数据的基本代码示例。
示例使用了位于 EXAMPLEMODULE
模块中 UCaptureAudioClassExample
类的 CaptureAudioExample
函数。
注意:要成功运行示例,请确保在 .Build.cs 文件的 PublicDependencyModuleNames
或 PrivateDependencyModuleNames
中添加 RuntimeAudioImporter
模块,以及在项目的 .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);
}