optimize-audio
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCritical Rules
关键规则
- Do not make changes before reporting findings to the user
- Follow steps in strict order; never jump ahead
- STOP at every checkpoint and await the user's response before continuing
WAIT - Quality is more important than speed: measure before and after every change
- Always verify results in a device build; Editor audio stats are indicative only
- 在向用户报告发现结果前,请勿进行任何更改
- 严格按照步骤顺序操作,切勿跳步
- 在每个检查点处暂停,等待用户回复后再继续
WAIT - 质量优先于速度:每次更改前后都要进行测量
- 始终在设备构建中验证结果;编辑器音频统计仅作参考
0. Set up the execution path
0. 设置执行路径
Every C# step below runs inside a live Editor through the Unity CLI. The skill owns
getting you there — installing the CLI, confirming a connected Editor, adding the project's
package, telling a genuinely absent Editor apart from one stuck in Safe Mode,
and discovering the Editor's command catalog. Follow it first; don't re-derive any of it here.
unity-clicom.unity.pipelineTwo things it can't know for you:
- You need in particular, not just a reachable Editor. Confirm it appears in the catalog. Its presence depends on the Pipeline package version, not on the CLI, so a healthy install can still lack it — if it's missing, say so and stop.
eval - Do not hand-edit files to change import settings. Importer values only take effect through
.metain a live Editor, so an unreachable Editor is a stop, not a cue to edit metadata directly.SaveAndReimport()
Run C# with . Discover the parameter shape from
rather than assuming one. defaults to a 30 second
timeout.
unity command eval --code '<snippet>'unity command --format jsonunity command以下所有C#步骤都通过Unity CLI在运行中的编辑器内执行。技能负责帮你完成前期准备——安装CLI、确认已连接编辑器、添加项目的包、区分编辑器确实未运行和陷入安全模式的情况,以及发现编辑器的命令目录。请先遵循该技能的流程;请勿在此处重复推导相关内容。
unity-clicom.unity.pipeline有两件事它无法为你判断:
- 你特别需要命令,而不仅仅是可连接的编辑器。请确认它出现在命令目录中。它是否存在取决于Pipeline包的版本,而非CLI,因此即使安装正常也可能缺少该命令——如果缺失,请告知用户并停止操作。
eval - 请勿手动编辑文件来修改导入设置。导入器的值只有通过运行中编辑器的
.meta才能生效,因此如果无法连接编辑器,应停止操作,而非直接编辑元数据。SaveAndReimport()
使用运行C#代码。请通过了解参数格式,而非自行假设。默认超时时间为30秒。
unity command eval --code '<snippet>'unity command --format jsonunity commandPassing C# to eval
eval向eval
传递C#代码
evaleval- No directives. The compiler reads
usingas a resource-disposal statement and rejects it (using UnityEngine;).CS0210 - Types must be fully qualified. A bare or
AssetDatabasedoes not resolve (AudioImporter/CS0246), and a bareCS0103is ambiguous withObject(object).CS0104
The recipes in resources/audio-import-api.md are written
fully qualified so they can be passed to as-is.
evaleval- 不支持指令。编译器会将
using视为资源释放语句并拒绝执行(错误码using UnityEngine;)。CS0210 - 类型必须完全限定。直接使用或
AssetDatabase无法解析(错误码AudioImporter/CS0246),直接使用CS0103会与Object产生歧义(错误码object)。CS0104
resources/audio-import-api.md中的示例代码已采用完全限定格式,可直接传递给使用。
eval1. Pre-Flight: Detect Audio System
1. 预检查:检测音频系统
Before doing anything else, establish the audio environment:
- Detect platform and sample rate: Use to read
evalandEditorUserBuildSettings.activeBuildTarget. The output sample rate affects whether overriding clip sample rates will actually save memory.AudioSettings.outputSampleRate - Detect AudioMixer presence: Use the mixer-asset query recipe in resources/audio-import-api.md to see if a mixer graph exists. If none exists, note that routing and effect costs are not a concern.
- Detect AudioListener: Use the scene-component query recipe in resources/audio-import-api.md for to confirm exactly one listener is present. Multiple listeners produce incorrect spatialization; zero listeners produce silence.
UnityEngine.AudioListener - Proceed only after platform and listener state are confirmed.
在进行任何操作前,先确定音频环境:
- 检测平台和采样率:使用读取
eval和EditorUserBuildSettings.activeBuildTarget。输出采样率会影响覆盖音频片段采样率是否真的能节省内存。AudioSettings.outputSampleRate - 检测AudioMixer是否存在:使用resources/audio-import-api.md中的混音器资源查询示例,查看是否存在混音器图。如果不存在,则无需关注路由和效果开销。
- 检测AudioListener:使用resources/audio-import-api.md中的场景组件查询示例,查找,确认恰好存在一个监听器。多个监听器会导致空间化错误;零个监听器会导致无声。
UnityEngine.AudioListener - 仅在确认平台和监听器状态后继续操作。
2. Assess Current State
2. 评估当前状态
Before recommending any change, gather observable data:
- Find all AudioSources: Use the scene-component query recipe in resources/audio-import-api.md for . For each result, use one
UnityEngine.AudioSourcecall to batch-read properties — see the batch read recipe in resources/audio-import-api.md.eval - Inspect mixer topology: If a mixer was found in Pre-Flight, use to read the AudioMixer's exposed parameters and group count. A group count above ~8 or effects on the Master group are immediate flags.
eval - Check DSP buffer size: Use the DSP buffer recipe in resources/audio-import-api.md to read buffer size. See DSP Buffer Size Guidelines in resources/platform-settings.md for recommended values.
- Report findings before making changes: Summarize ALL detected sources, the listener count, and mixer depth to the user. Flag any immediate risks (e.g., stereo clip with , Decompress On Load on a clip > 1 MB, reverb on the Master group).
spatialBlend = 1
WAIT for the user to review the assessment before proceeding.
在推荐任何更改前,先收集可观测数据:
- 查找所有AudioSource:使用resources/audio-import-api.md中的场景组件查询示例,查找。对于每个结果,使用一次
UnityEngine.AudioSource调用批量读取属性——请参考resources/audio-import-api.md中的批量读取示例。eval - 检查混音器拓扑结构:如果在预检查中发现混音器,使用读取AudioMixer的暴露参数和组数量。组数量超过约8个,或Master组上存在效果,都是需要立即关注的标志。
eval - 检查DSP缓冲区大小:使用resources/audio-import-api.md中的DSP缓冲区示例读取缓冲区大小。请参考resources/platform-settings.md中的DSP缓冲区大小指南获取推荐值。
- 在进行更改前报告发现结果:向用户总结所有检测到的音频源、监听器数量以及混音器深度。标记任何即时风险(例如,的立体声片段、大小超过1 MB且设置为Decompress On Load的片段、Master组上的混响效果)。
spatialBlend = 1
等待用户评估结果后再继续操作。
3. Understand Request
3. 理解用户需求
Route to the correct section based on what the user needs:
| User Says | Path |
|---|---|
| "audio memory too high" / "memory profiler shows audio" | Section 4 — Import settings audit |
| "load times slow" / "decompression stall" | Section 4 — Load Type review |
| "DSP spike" / "mixer CPU" / "audio CPU high" | Section 4B — Mixer audit |
| "3D sound wrong" / "only left channel plays" / "stereo in 3D" | Section 4A — Force To Mono + spatial settings |
| "quality artifacts" / "voice sounds bad" / "Vorbis crackling" | Section 4C — Compression quality tuning |
| "mobile audio battery" / "mobile memory" | Section 4D — Mobile sample rate override |
| "set import settings on all clips" / "batch audio settings" | Section 4 — Bulk import audit |
| "streaming" / "background loading" / "Addressables audio" | Section 4E — Streaming and async load |
If the symptom is ambiguous, ask: "Is the problem audio memory usage, DSP CPU spikes, or audio playback quality?"
根据用户需求路由到对应章节:
| 用户表述 | 对应路径 |
|---|---|
| "音频内存占用过高" / "内存分析器显示音频占用高" | 第4节——导入设置审核 |
| "加载速度慢" / "解压缩卡顿" | 第4节——Load Type检查 |
| "DSP峰值" / "混音器CPU占用高" / "音频CPU占用高" | 第4B节——混音器审核 |
| "3D声音异常" / "仅左声道播放" / "3D场景中的立体声" | 第4A节——强制单声道+空间设置 |
| "音质失真" / "语音音质差" / "Vorbis格式有杂音" | 第4C节——压缩质量调优 |
| "移动端音频耗电" / "移动端内存占用高" | 第4D节——移动端采样率覆盖 |
| "为所有片段设置导入设置" / "批量音频设置" | 第4节——批量导入审核 |
| "流式播放" / "后台加载" / "Addressables音频" | 第4E节——流式播放与异步加载 |
如果症状不明确,请询问:"问题是音频内存占用过高、DSP CPU峰值,还是音频播放质量问题?"
4. Primary Diagnostic Workflow
4. 主要诊断流程
Use the findings from Section 2 to determine which sub-section applies. More than one may apply simultaneously.
根据第2节的发现结果确定适用的子章节。可能同时适用多个子章节。
4A. Force To Mono and Spatial Settings
4A. 强制单声道与空间设置
For any AudioSource where (3D positioned sound):
spatialBlend > 0- Check clip channel count: Use to read
eval. IfaudioSource.clip.channelsandchannels == 2, only the left channel plays — this is a bug, not a feature.spatialBlend == 1 - Recommend Force To Mono: Use the read importer recipe in resources/audio-import-api.md to inspect current settings, then apply Force To Mono using the force-to-mono recipe.
- Apply and reimport: Report before/after channel counts to the user.
- Verify spatial blend: Use to confirm
evalisaudioSource.spatialBlend(full 3D) and1.0is set to an appropriate curve.audioSource.rolloffMode
对于任何的AudioSource(3D定位声音):
spatialBlend > 0- 检查片段声道数:使用读取
eval。如果audioSource.clip.channels且channels == 2,则仅左声道会播放——这是一个bug,而非特性。spatialBlend == 1 - 建议启用强制单声道:使用resources/audio-import-api.md中的读取导入器示例检查当前设置,然后使用强制单声道示例启用该设置。
- 应用设置并重新导入:向用户报告更改前后的声道数。
- 验证空间混合设置:使用确认
eval为audioSource.spatialBlend(完全3D),且1.0设置为合适的曲线。audioSource.rolloffMode
4B. AudioMixer Audit
4B. AudioMixer审核
-
Measure group depth: Useto walk the mixer's group tree and count levels. More than 3 levels (Master → SFX / Music / Voice → sub-bus) adds routing overhead every frame, even when children are silent.
eval -
Check effects on silent groups: Useto query each group's effects list. Effects such as
evalrun their DSP at full cost even when no AudioSource routes to that group.AudioReverbFilter -
Flag SFX Reverb on parent groups: This is the most expensive built-in effect. If found on the Master or a high-level group, flag it explicitly.
-
Present recommendations to the user:
- Remove or bypass effects on groups that have no active sources.
- Use snapshots to switch mix states (combat / explore / pause) rather than toggling effects at runtime.
- Flatten unnecessary sub-buses; redirect sources to a shallower ancestor.
WAIT for the user to approve the mixer changes before applying. -
Verify DSP buffer size: Iffrom Pre-Flight is very small (< 256), recommend increasing it — see DSP Buffer Size Guidelines in resources/platform-settings.md.
bufferLength
-
测量组深度:使用遍历混音器的组树并计算层级。超过3个层级(Master → SFX / Music / Voice → 子总线)会增加每帧的路由开销,即使子组处于静默状态。
eval -
检查静默组上的效果:使用查询每个组的效果列表。诸如
eval之类的效果即使没有AudioSource路由到该组,也会以全开销运行DSP。AudioReverbFilter -
标记父组上的SFX混响:这是最耗费性能的内置效果。如果在Master组或高层组上发现该效果,请明确标记。
-
向用户呈现建议:
- 移除或绕过没有活动音频源的组上的效果。
- 使用快照切换混音状态(战斗/探索/暂停),而非在运行时切换效果。
- 扁平化不必要的子总线;将音频源重定向到层级更浅的祖先组。
等待用户批准混音器更改后再应用。 -
验证DSP缓冲区大小:如果预检查中的非常小(<256),建议增大该值——请参考resources/platform-settings.md中的DSP缓冲区大小指南。
bufferLength
4C. Compression Quality Tuning
4C. 压缩质量调优
- Read current compression format: Use the read importer recipe in resources/audio-import-api.md to read and
compressionFormatfor the clips reported by the user.quality - Apply the platform matrix: See the Compression Format Matrix in resources/platform-settings.md for per-platform recommendations.
- Warn about lossy sources: Use the lossy source check recipe in resources/audio-import-api.md. If the original file is MP3, warn the user that lossy source quality is lost permanently after Unity re-encodes. Recommend WAV or AIFF sources.
- 读取当前压缩格式:使用resources/audio-import-api.md中的读取导入器示例,读取用户报告的片段的和
compressionFormat。quality - 应用平台矩阵:请参考resources/platform-settings.md中的压缩格式矩阵获取各平台的推荐设置。
- 警告有损源文件:使用resources/audio-import-api.md中的有损源文件检查示例。如果原始文件是MP3,警告用户Unity重新编码后会永久丢失有损源文件的质量。建议使用WAV或AIFF源文件。
4D. Mobile Sample Rate Override
4D. 移动端采样率覆盖
- Identify SFX clips on mobile target: Use the scene-component query recipe for and filter for non-music, non-dialogue clips.
UnityEngine.AudioSource - Read current sample rate setting: Use the read importer recipe in resources/audio-import-api.md to read and
sampleRateSettingfor each clip.sampleRateOverride - Apply mobile override: Use the sample rate override recipe in resources/audio-import-api.md. See Sample Rate Recommendations in resources/platform-settings.md for per-use-case rates.
- Report savings: Halving the sample rate halves the PCM memory cost. Report the estimated saving for each clip changed.
- 识别移动端目标上的SFX片段:使用的场景组件查询示例,过滤出非音乐、非对话的片段。
UnityEngine.AudioSource - 读取当前采样率设置:使用resources/audio-import-api.md中的读取导入器示例,读取每个片段的和
sampleRateSetting。sampleRateOverride - 应用移动端覆盖设置:使用resources/audio-import-api.md中的采样率覆盖示例。请参考resources/platform-settings.md中的采样率推荐获取各使用场景的推荐值。
- 报告节省的资源:将采样率减半会使PCM内存成本减半。报告每个更改片段的预估节省量。
4E. Load Type and Streaming
4E. Load Type与流式播放
- Audit Load Type per clip: Use to read
evalfor each clip found in Section 2.clip.loadType - Apply the decision rule: See Load Type Decision Table in resources/platform-settings.md.
- Flag mismatches: See Load Type Mismatch Flags in resources/platform-settings.md. Report both types of mismatches to the user.
- Apply for any Streaming clip — use the Load In Background recipe in resources/audio-import-api.md.
Load In Background
- 审核每个片段的Load Type:使用读取第2节中找到的每个片段的
eval。clip.loadType - 应用决策规则:请参考resources/platform-settings.md中的Load Type决策表。
- 标记不匹配项:请参考resources/platform-settings.md中的Load Type不匹配标记。向用户报告两种类型的不匹配项。
- 为流式播放片段启用——使用resources/audio-import-api.md中的Load In Background示例。
Load In Background
5. Validation
5. 验证
After any import setting or mixer change:
- Re-read clip stats: Use to re-read
eval,clip.loadType,clip.channels, and the importer'sAudioSettings.outputSampleRateto confirm the change applied after reimport.compressionFormat - Confirm AudioSource routing: Use the scene-component query recipe for and verify
UnityEngine.AudioSourceis assigned as expected after any mixer restructure.audioSource.outputAudioMixerGroup - Report delta: State the before and after values for each setting changed. Do not assume the change was effective without reading back the applied importer values.
- Iterate limit: Maximum 3 adjust-and-verify cycles before pausing to ask the user for feedback.
在进行任何导入设置或混音器更改后:
- 重新读取片段统计信息:使用重新读取
eval、clip.loadType、clip.channels以及导入器的AudioSettings.outputSampleRate,确认重新导入后更改已生效。compressionFormat - 确认AudioSource路由:使用的场景组件查询示例,验证任何混音器重构后
UnityEngine.AudioSource是否按预期分配。audioSource.outputAudioMixerGroup - 报告变化值:说明每个更改设置的前后值。不要假设更改已生效,必须读取已应用的导入器值进行确认。
- 迭代限制:最多进行3次调整-验证循环,之后暂停并向用户反馈。
6. Troubleshooting
6. 故障排除
Stereo clip on a 3D AudioSource — only left channel audible
3D AudioSource使用立体声片段——仅左声道可闻
- Confirm .
audioSource.spatialBlend == 1 - Confirm .
audioSource.clip.channels == 2 - Enable in the AudioClip importer and reimport. Unity mixes both channels to mono during import, preserving level with
forceToMono(keep on).normalize = true - If the user does not want to reimport: set as a runtime workaround, but warn this does not recover stereo information.
audioSource.panStereo = 0
- 确认。
audioSource.spatialBlend == 1 - 确认。
audioSource.clip.channels == 2 - 在AudioClip导入器中启用并重新导入。Unity会在导入过程中将两个声道混合为单声道,同时保持
forceToMono(保持启用状态)以维持音量。normalize = true - 如果用户不想重新导入:设置作为运行时解决方法,但警告这无法恢复立体声信息。
audioSource.panStereo = 0
Decompress On Load clip causes memory spike
Decompress On Load片段导致内存峰值
- Confirm and
clip.loadType == AudioClipLoadType.DecompressOnLoadis long (> 5 s).clip.length - Switch to if it is music or ambience,
Streamingif played only occasionally.CompressedInMemory - If the clip is short but still large: check (stereo wastes double the memory) and
clip.channels(high sample rate on a mobile target wastes memory). Apply Force To Mono and/or sample rate override.clip.frequency
- 确认且
clip.loadType == AudioClipLoadType.DecompressOnLoad较长(>5秒)。clip.length - 如果是音乐或环境音,切换为;如果仅偶尔播放,切换为
Streaming。CompressedInMemory - 如果片段较短但仍较大:检查(立体声会浪费双倍内存)和
clip.channels(移动端目标使用高采样率会浪费内存)。应用强制单声道和/或采样率覆盖设置。clip.frequency
AudioMixer CPU spike — DSP thread hot
AudioMixer CPU峰值——DSP线程占用高
- Confirm with the mixer-asset query recipe that the mixer graph exists.
- Use to list all groups and their attached effects. Look for reverb, chorus, or EQ on high-level groups.
eval - Move expensive effects down to leaf groups that are only active when sources are playing.
- Use snapshots to bypass effect chains during gameplay states where they are not heard (e.g., bypass reverb during a menu).
- If the DSP buffer is small (64 or 128 samples), raise it — see DSP Buffer Size Guidelines in resources/platform-settings.md.
- 使用混音器资源查询示例确认混音器图存在。
- 使用列出所有组及其附加的效果。查找高层组上的混响、合唱或均衡器效果。
eval - 将耗费性能的效果下移到仅在音频源播放时才活跃的叶组。
- 使用快照在不需要听到效果的游戏状态下绕过效果链(例如,菜单期间绕过混响)。
- 如果DSP缓冲区较小(64或128样本),增大该值——请参考resources/platform-settings.md中的DSP缓冲区大小指南。
Vorbis quality artifacts on dialogue
对话使用Vorbis格式出现音质失真
- Confirm .
defaultSampleSettings.compressionFormat == AudioCompressionFormat.Vorbis - Confirm — default is 0.5, which is often audible on voice. Raise to 0.7–0.85.
defaultSampleSettings.quality - On iOS: switch to AAC instead of Vorbis (hardware decode, better quality at equivalent bitrate).
- Confirm the source file is lossless (WAV or AIFF). MP3 sources cannot recover quality lost before Unity's re-encode.
- 确认。
defaultSampleSettings.compressionFormat == AudioCompressionFormat.Vorbis - 确认——默认值为0.5,这通常会导致语音音质可闻失真。将其提高到0.7–0.85。
defaultSampleSettings.quality - 在iOS上:切换为AAC而非Vorbis(硬件解码,在等效比特率下音质更好)。
- 确认源文件为无损格式(WAV或AIFF)。MP3源文件无法恢复Unity重新编码前丢失的质量。
AudioListener count is not exactly one
AudioListener数量不是恰好一个
- Zero listeners: All audio will be silent. Use to add an
evalcomponent to the main camera:AudioListener.UnityEngine.Camera.main.gameObject.AddComponent<UnityEngine.AudioListener>() - Multiple listeners: Unity uses the last enabled one, producing unpredictable spatialization. Use the scene-component query recipe for and disable all but the intended one.
UnityEngine.AudioListener
- 零个监听器:所有音频都会无声。使用为主相机添加
eval组件:AudioListener。UnityEngine.Camera.main.gameObject.AddComponent<UnityEngine.AudioListener>() - 多个监听器:Unity会使用最后启用的监听器,导致不可预测的空间化效果。使用的场景组件查询示例,禁用除目标监听器外的所有监听器。
UnityEngine.AudioListener
Load In Background
causes first-play silence
Load In BackgroundLoad In Background
导致首次播放无声
Load In BackgroundThis is expected behavior: the clip has not finished loading when is first called. Mitigate with:
Play()- Preload the clip at scene start by calling before it is needed.
clip.LoadAudioData() - Use with a slight delay to allow async load to complete.
AudioSource.PlayScheduled() - For AudioSources that must play immediately: switch to (synchronous on first play) rather than
CompressedInMemorywith background load.Streaming
这是预期行为:首次调用时片段尚未完成加载。可通过以下方式缓解:
Play()- 在场景启动时预加载片段,在需要播放前调用。
clip.LoadAudioData() - 使用并设置轻微延迟,以允许异步加载完成。
AudioSource.PlayScheduled() - 对于必须立即播放的AudioSource:切换为(首次播放为同步加载),而非启用后台加载的
CompressedInMemory。Streaming
7. Completion
7. 完成
After finishing the audit or optimization:
- Summarize every setting changed with before/after values.
- List any clips or groups that still need attention (e.g., clips that require on-device measurement to confirm savings).
- If the user needs runtime memory measurement, point them at the Memory Profiler package, which reports the largest AudioClips by runtime byte cost.
- If mixer CPU is still high after the audit, point them at the Unity Profiler's Audio module for DSP thread profiling.
完成审核或优化后:
- 总结所有更改的设置及其前后值。
- 列出仍需关注的片段或组(例如,需要在设备上测量才能确认节省量的片段)。
- 如果用户需要运行时内存测量,引导他们使用Memory Profiler包,该包会按运行时字节成本报告最大的AudioClip。
- 如果审核后混音器CPU占用仍然很高,引导他们使用Unity Profiler的Audio模块进行DSP线程分析。
Detailed References
详细参考
- Platform settings, compression matrix, load types, sample rates: resources/platform-settings.md
- AudioImporter API recipes and code patterns: resources/audio-import-api.md
- 平台设置、压缩矩阵、Load Type、采样率:resources/platform-settings.md
- AudioImporter API示例和代码模式:resources/audio-import-api.md
See Also
另请参阅
- Memory Profiler package — finds the largest AudioClips by runtime byte cost.
- Unity Profiler, Audio module — DSP CPU markers and frame-time budget.
- — creating mixers and routing Audio Sources into groups.
audio-setup-mixers
- Memory Profiler包——按运行时字节成本查找最大的AudioClip。
- Unity Profiler,Audio模块——DSP CPU标记和帧时间预算。
- ——创建混音器并将Audio Source路由到组中。
audio-setup-mixers