播放音频
基本播放
要播放导入的声波,请使用与播放普通声波相同的函数。例如,使用 PlaySound2D 或来自音频组件(如 Sound Cue)的 Play 函数。

控制播放
倒回播放时间
要倒回声波的播放时间,请使用 RewindPlaybackTime 函数。
- 蓝图
- C++

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Rewind playback time of the sound wave for 12.5 seconds
ImportedSoundWave->RewindPlaybackTime(12.5f);
备注
在UE 4.27及更早版本中,如果你想从大于0的特定时间开始播放,可能需要事先使用RewindPlaybackTime函数。否则,由于引擎内部处理程序化波形的问题,声音可能无法正确播放。此问题自5.0版本起已在引擎中得到解决。
获取播放信息
要获取声波的当前播放时间,请使用 GetPlaybackTime 或 GetPlaybackPercentage 函数。你还可以使用 GetDuration 函数获取声波的时长。
- 蓝图
- C++

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Get the current playback time of the sound wave
float PlaybackTime = ImportedSoundWave->GetPlaybackTime();
// Get the current playback percentage of the sound wave
float PlaybackPercentage = ImportedSoundWave->GetPlaybackPercentage();
// Get the duration of the sound wave
float Duration = ImportedSoundWave->GetDuration();
检查播放状态
当前正在播放
要判断声波当前是否正在播放,可以使用 IsPlaying 函数。
- 蓝图
- C++

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Check if the sound wave is currently playing
bool bIsPlaying = ImportedSoundWave->IsPlaying();
播放是否已完成
要检查声波是否已播放完毕,你可以使用 IsPlaybackFinished 函数。
- 蓝图
- C++

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Check if the sound wave has finished playback
bool bIsFinished = ImportedSoundWave->IsPlaybackFinished();
停止播放
你可以使用 StopPlayback 函数来停止声波播放。
- 蓝图
- C++

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Stop the playback of the sound wave
ImportedSoundWave->StopPlayback();
信息
通常建议通过外部方式(例如在音频组件上调用 Stop)停止声波播放,并在没有外部方式可用时使用此函数。另外请注意,此函数不适用于从 MetaSounds 播放。
事件处理
跟踪播放完成情况
要跟踪音频播放结束,请绑定到 OnAudioPlaybackFinished 委托。
- 蓝图
- C++

UCLASS()
class AMyAudioPlayer : public AActor
{
GENERATED_BODY()
public:
UFUNCTION()
void OnAudioFinished()
{
// Handle the end of audio playback
}
void BindAudioDelegate(UImportedSoundWave* ImportedSoundWave)
{
// Bind to the OnAudioPlaybackFinished delegate
ImportedSoundWave->OnAudioPlaybackFinished.AddDynamic(this, &AMyAudioPlayer::OnAudioFinished);
}
};
内存管理
释放内存
你可以使用 ReleaseMemory 函数手动清除音频数据。
- 蓝图
- C++

// Release memory of the sound wave
ImportedSoundWave->ReleaseMemory();
注意
除非你有特定的内存管理需求或已禁用垃圾回收器,否则不建议手动释放内存。
释放已播放的音频数据
要在播放期间自动释放音频缓冲区中已播放的部分,请使用 SetPlayedAudioDataReleaseSettings 函数配置释放设置。
- 蓝图
- C++

FPlayedAudioDataReleaseSettings ReleaseSettings;
ReleaseSettings.bReleasePlayedAudioData = true;
ReleaseSettings.ReleaseCallbackFrequency = 50;
ReleaseSettings.MinFramesToRelease = 44100;
// Configure automatic release of the already-played audio data
ImportedSoundWave->SetPlayedAudioDataReleaseSettings(ReleaseSettings);
bReleasePlayedAudioData- 是否启用释放。默认禁用ReleaseCallbackFrequency- 释放检查之间音频生成请求(对OnGeneratePCMAudio的调用)的次数MinFramesToRelease- 触发释放所需的最小已播放帧数
注意
启用此项会限制在已释放点之前进行回退/跳转,因为该音频数据已被物理释放,无法再播放。