播放音频
基础播放
要播放一个导入的 Sound Wave,使用与播放常规 Sound Wave 相同的函数。例如,使用 PlaySound2D 函数或来自音频组件(如 Sound Cue)的 Play 函数。

控制播放
回退播放时间
要回退 Sound Wave 的播放时间,请使用 RewindPlaybackTime 函数。
- Blueprint
- 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 函数来获取声波的持续时间。
- Blueprint
- 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 函数。
- Blueprint
- C++

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

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

// Assuming ImportedSoundWave is a UE reference to a UImportedSoundWave object
// Stop the playback of the sound wave
ImportedSoundWave->StopPlayback();
信息
通常建议使用外部方法(例如,在音频组件上调用 Stop)来停止声波播放,如果外部方法不可用,则使用此函数。另外请注意,此函数不适用于来自 MetaSounds 的播放。
事件处理
跟踪播放完成
要跟踪音频播放的结束,请绑定到 OnAudioPlaybackFinished 委托。
- Blueprint
- 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 函数手动清除音频数据。
- Blueprint
- C++

// Release memory of the sound wave
ImportedSoundWave->ReleaseMemory();
注意
除非您有特定的内存管理需求或已禁用垃圾回收器,否则不建议手动释放内存。