图像与设计
在 Unreal Engine…
当需要在 UE 项目中设计、播放、控制、优化或分析 2D/3D 音频、MetaSound、Submix 与并发时使用。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 38/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 59/100 ×0.15
适用场景
在 Unreal Engine 中实现和特定
解决思路
- 实现前读取 `.agents/ue-project-context.md`,确认启用的音频插件(Resonance Audio、Steam Audio、Wwise、FMOD、MetaSound 插件版本)、目标平台、Dedicated server 标志、VR 标志。
- 明确需求:一次性 SFX、循环环境、音乐、UI 反馈、对话;空间化跟随 actor 还是全局 2D;并发关注(枪声、脚步、爆炸);运行时控制(淡入淡出、暂停、参数变化);MetaSound 程序化还是预创作 SoundCue/SoundWave。
- 按资产层级选择:USoundBase 抽象基类;USoundWave 原始 PCM/压缩音频;USoundCue 节点图;UMetaSoundSource 程序化音频图。
- 导入 .wav/.ogg/.flac 为 USoundWave,并在资产上设置 SoundClassObject 和 AttenuationSettings。
- 使用 USoundCue 节点图组合多个 wave,可用 USoundNodeRandom、USoundNodeModulator、USoundNodeMixer、USoundNodeAttenuation、USoundNodeLooping、USoundNodeDelay、USoundNodeDistanceCrossFade。
- 使用 UMetaSoundSource 声明类型输入(float、bool、int32、trigger),运行时通过 UAudioComponent::SetFloatParameter、SetBoolParameter、SetIntParameter 设置。
- 对超过约 30 秒的音乐/环境,设置 USoundWave::LoadingBehavior:短 SFX 用 ESoundWaveLoadingBehavior::ForceInline;关卡开始时加载的音乐用 RetainOnLoad;长文件用 LoadOnDemand;编辑器路径 SoundWave asset → Details → Loading → Loading Behavior。
- 2D 非空间化播放用 UGameplayStatics::PlaySound2D(this, ImpactSound, 1.0f, 1.0f, 0.0f, ConcurrencySettings, OwningActor)。
- 3D 空间化一次性播放用 UGameplayStatics::PlaySoundAtLocation,传位置、旋转、音量、音高、StartTime、AttenuationOverride、ConcurrencyOverride、OwningActor;需在声音资产有 AttenuationSettings。
- 需要句柄时用 UGameplayStatics::SpawnSoundAtLocation 返回 UAudioComponent*;bAutoDestroy=true 时播完自动销毁。
- 附着移动组件用 UGameplayStatics::SpawnSoundAttached,传 Sound、AttachToComponent、Socket、相对位置/旋转、EAttachLocation::SnapToTargetIncludingScale、bStopWhenAttachedToDestroyed、音量、音高、StartTime、Attenuation、Concurrency、bAutoDestroy;循环时 bAutoDestroy=false。
- 永久 UAudioComponent 在构造函数中用 CreateDefaultSubobject<UAudioComponent>(TEXT("AudioComponent")),SetupAttachment(RootComponent),bAutoActivate=false,bStopWhenOwnerDestroyed=true。
- 播放控制:SetSound、Play(StartTime)、Stop、SetPaused、FadeIn、FadeOut、SetVolumeMultiplier、SetPitchMultiplier;用 GetPlayState 查询 EAudioComponentPlayState(Playing、Stopped、Paused、FadingIn、FadingOut)。
- 委托绑定:OnAudioFinished、OnAudioPlaybackPercent、OnAudioPlayStateChanged 用 AddDynamic;native 版本 OnAudioFinishedNative、OnAudioPlaybackPercentNative 用 AddUObject 避免 GC 开销。
- 衰减:用 USoundAttenuation/FSoundAttenuationSettings;通过 USoundBase::AttenuationSettings 分配,或作为播放函数 override 传入。
- 选择衰减形状 EAttenuationShape:Sphere(默认全向)、Capsule(长声源)、Box(房间)、Cone(方向性)。
- 选择距离模型 EAttenuationDistanceModel:Linear、Logarithmic、NaturalSound(推荐)、Inverse、LogReverse、Custom。
- 配置 FSoundAttenuationSettings:bAttenuate、bSpatialize、SpatializationAlgorithm(SPATIALIZATION_Default/SPATIALIZATION_HRTF)、bAttenuateWithLPF、LPFRadiusMin、LPFRadiusMax、LPFFrequencyAtMin、LPFFrequencyAtMax。
- 配置监听者聚焦:bEnableListenerFocus、FocusAzimuth、NonFocusAzimuth、FocusDistanceScale、NonFocusVolumeAttenuation。
- 配置遮挡:bEnableOcclusion、OcclusionTraceChannel(如 ECC_Visibility)、OcclusionLowPassFilterFrequency、OcclusionVolumeAttenuation、OcclusionInterpolationTime。
- 配置混响发送:bEnableReverbSend、ReverbSendMethod(Linear、CustomCurve、Manual)、ReverbWetLevelMin/Max、ReverbDistanceMin/Max。
- 配置优先级衰减:bEnablePriorityAttenuation、PriorityAttenuationMin/Max。
- 在 UAudioComponent 内联覆盖衰减:bOverrideAttenuation=true,设置 AttenuationOverrides.bAttenuate=true、bSpatialize=true、FalloffDistance=3000.f 等。
- Audio LOD:用 bAttenuateWithLPF=true 和 LPFRadiusMin/LPFRadiusMax 在完全衰减前低通远距离声音;背景环境设 bEnableSendToAudioLink=false;USoundBase::Priority(0.0–100.0,默认 1.0,越高越重要)决定达到 Audio Settings 最大声道数时哪些 voice 保留。
- 并发:用 USoundConcurrency 控制同时 voice;通过 USoundBase::ConcurrencySet(TSet<USoundConcurrency*>)或 ConcurrencyOverrides(bOverrideConcurrency=true)分配。
- 配置 FSoundConcurrencySettings:MaxCount、bLimitToOwner、ResolutionRule(PreventNew、StopOldest、StopFarthestThenPreventNew、StopFarthestThenOldest、StopLowestPriority、StopQuietest、StopLowestPriorityThenPreventNew)、RetriggerTime、VoiceStealReleaseTime、VolumeScaleMode(Default、Distance、Priority)、VolumeScaleAttackTime、VolumeScaleReleaseTime;用 USoundBase::Priority 决定 MaxCount 下哪些保留。
- Submix 层级:USoundSubmixBase → USoundSubmixWithParentBase → USoundSubmix/USoundfieldSubmix;UEndpointSubmix 用于外部端点(触觉、额外设备);典型树 Master > {Music, SFX, Voice, Ambient};Music submix 设 bMuteWhenBackgrounded=true。
- 运行时 submix 控制:SetSubmixOutputVolume、SetSubmixWetLevel、SetSubmixDryLevel;DynamicConnect/DynamicDisconnect 动态父子连接。
- Submix effect chain:SubmixEffectChain 存放 USoundEffectSubmixPreset;运行时可用 USubmixEffectReverbPreset 设置 Settings.Density、Diffusion、DecayTime 并 Add 到 ReverbSubmix->SubmixEffectChain;EQ 用 USubmixEffectEQPreset,dynamics 也用相应 preset。
- Sound classes:用 SoundClassObject 分配;定义与 submix 平行的 volume/pitch 层级。
- Sound Mix modifiers:先用 UGameplayStatics::SetBaseSoundMix 设置基础 mix;用 PushSoundMixModifier 叠加;用 PopSoundMixModifier 移除;用 ClearSoundMixModifiers 清空;USoundMix assets 定义每 USoundClass 的 volume/pitch 调整,用于战斗/潜行/水下。
- MetaSounds:UMetaSoundSource 派生 USoundBase,可播放位置同 USoundBase;UAudioComponent 实现 ISoundParameterControllerInterface,用 SetFloatParameter、SetBoolParameter、SetIntParameter、SetTriggerParameter、ResetParameters 控制。
- 选择 SoundCue 还是 MetaSound:SoundCue 适合运行时参数有限、程序化音频否、通过参数节点反应游戏、随机预创作声音;MetaSound 适合类型化输入、完整参数系统、程序化音频(振荡器、噪声、DSP 滤波器)、原生绑定 float/bool/trigger、自适应音乐/程序化 SFX/状态驱动音频。
- Submix 包络跟随:SFXSubmix->StartEnvelopeFollowing(this);创建 FOnSubmixEnvelopeBP 并 BindDynamic;AddEnvelopeFollowerDelegate;StopEnvelopeFollowing;回调 OnSubmixEnvelope(const TArray<float>& Envelope)。
- Submix 频谱分析:SFXSubmix->StartSpectralAnalysis(this, EFFTSize::Medium, EFFTPeakInterpolationMethod::Linear, EFFTWindowType::Hann, 0.0f, EAudioSpectrumType::MagnitudeSpectrum);创建 TArray<FSoundSubmixSpectralAnalysisBandSettings>,设置 BandFrequency、AttackTimeMsec、ReleaseTimeMsec;用 FOnSubmixSpectralAnalysisBP BindDynamic;AddSpectralAnalysisDelegate(this, Bands, Spectral, 30.f, -40.f, true, false);StopSpectralAnalysis;回调 OnSpectralAnalysis(const TArray<float>& Magnitudes)。
- 模块依赖:.Build.cs 的 PublicDependencyModuleNames 添加 Engine、AudioMixer;MetaSound 参数添加 MetasoundEngine、MetasoundFrontend;包含 Components/AudioComponent.h、Kismet/GameplayStatics.h、Sound/SoundBase.h、Sound/SoundCue.h、Sound/SoundWave.h、Sound/SoundAttenuation.h、Sound/SoundConcurrency.h、Sound/SoundSubmix.h。
- NRT 分析:UAudioAnalyzerNRT 是离线分析抽象基类;ULoudnessNRT、UOnsetNRT 派生自 UAudioSynesthesiaNRT 再到 UAudioAnalyzerNRT;使用 Audio Synesthesia 插件,.Build.cs 添加 AudioSynesthesia,包含 AudioSynesthesiaModule.h。
- LoudnessNRT:NewObject<ULoudnessNRT>,NewObject<ULoudnessNRTSettings>,设置 Settings->AnalysisPeriod=0.01f,Analyzer->Settings=Settings,Analyzer->Sound=MySoundWave,Analyzer->AnalyzeAudio()(仅 WITH_EDITOR),GetLoudnessAtTime(1.5f, Loudness)。
- OnsetNRT 节拍检测:NewObject<UOnsetNRT>,OnsetAnalyzer->Sound=MySoundWave,OnsetAnalyzer->AnalyzeAudio()(仅 WITH_EDITOR),GetNormalizedChannelOnsetsBetweenTimes(0.f, Duration, 0, OnsetTimestamps, OnsetStrengths)。
- NRT 用途:预分析音轨生成 beat maps、loudness curves、onset markers;运行时使用这些数据做音乐驱动玩法,避免每帧 FFT 开销。
- 反模式:不要每次事件 NewObject<UAudioComponent>;一次性用 UGameplayStatics::PlaySoundAtLocation;重复/循环声音缓存单个 component,SpawnSoundAttached 时 bAutoDestroy=false,然后 Play。
- 反模式:不要播放无衰减的 3D 声音;传或分配 USoundAttenuation,并按游戏尺度调 sphere falloff。
- 反模式:不要忽略高频声音并发;传 USoundConcurrency,例如 MaxCount=4、ResolutionRule=StopFarthestThenOldest。
- 反模式:不要在 dedicated server 播放音频;用 if (GetNetMode() != NM_DedicatedServer) 守卫。
- 反模式:销毁前解绑委托;在 EndPlay 中 if (AudioComponent) { AudioComponent->OnAudioFinished.RemoveAll(this); AudioComponent->Stop(); }。
- 反模式:不要用 PlaySound2D 播世界内声音;用 PlaySoundAtLocation。
- 平台:Mobile 16–32 voice limit,积极使用并发,SFX 优先 resident loading,除非平台支持否则禁用 HRTF。
- 平台:Dedicated servers 用 GetNetMode() != NM_DedicatedServer 守卫所有音频调用。
- 平台:流式音频长音乐 SoundWave 设 LoadingBehavior=LoadOnDemand;不要 resident 加载数分钟音乐。
- App focus loss:在音乐/SFX submix 上设 bMuteWhenBackgrounded=true;自定义处理用 FCoreDelegates::ApplicationWillDeactivateDelegate.AddUObject(this, &UMyAudioManager::OnAppDeactivate),在 OnAppDeactivate 中取 FAudioDeviceHandle Device = GEngine->GetMainAudioDevice(),有效则 Device->SetTransientPrimaryVolume(0.f)。
- VR:所有 3D attenuation 资产启用 bSpatialize=true 和 SpatializationAlgorithm=SPATIALIZATION_HRTF。
- Audio LOD:用 bEnablePriorityAttenuation 在 voice 预算裁剪前降低远距离声音优先级。
适用边界 · 注意事项
- 不适用于非 Unreal Engine 项目。
- 涉及 MetaSound、AudioSynesthesia、HRTF 等具体能力时,需先确认对应插件/平台支持;未启用时不能直接照搬。
- 若项目使用 Wwise/FMOD 等第三方中间件作为主音频方案,本经验中的 UE 原生播放/Submix/MetaSound 做法可能不适用或只作参考。