> For the complete documentation index, see [llms.txt](https://docs.decentraland.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/audio-analysis.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 音频分析

从场景中播放的音频读取实时振幅和频率数据，以驱动响应式视觉效果。

该 `AudioAnalysis` 组件会读取场景中正在播放的音频源的实时数据，让你可以根据音乐驱动视觉效果。每一帧，它都会报告整体 **振幅** 值以及 **8 个频段** （从低频到高频），你可以用它们来缩放实体、改变实体颜色或制作动画。

常见用途：

* 随低音弹跳的立方体。
* 随节拍闪烁的灯光。
* 均衡器风格的柱状可视化效果。
* 随音乐变化的响应式材质或缩放道具。

`AudioAnalysis` 是只读数据流——场景只读取这些值，运行时负责填充数据。它适用于通过以下组件播放音频的实体： [AudioSource](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md)、 [AudioStream](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/audio-streaming.md)，或 [VideoPlayer](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/video-playing.md).

{% hint style="warning" %}
**📔 注意**: `AudioAnalysis` 目前仅受官方 Decentraland 桌面应用支持。在其他客户端中，该组件的值不会被填充，因此请确保即使收不到数据，场景也能正常运行。
{% endhint %}

## 最简示例

以下场景会播放声音，将 `AudioAnalysis` 附加到同一实体，并在每一帧根据音频的振幅缩放一个立方体。

```ts
import {
  engine,
  Transform,
  MeshRenderer,
  AudioSource,
  AudioAnalysis,
  AudioAnalysisView,
} from "@dcl/sdk/ecs";
import { Vector3 } from "@dcl/sdk/math";

export function main() {
  // 在实体上播放声音
  const audioEntity = engine.addEntity();
  Transform.create(audioEntity);
  AudioSource.create(audioEntity, {
    audioClipUrl: "sounds/music.mp3",
    playing: true,
    loop: true,
  });

  // 将 AudioAnalysis 附加到同一实体，以开始接收分析数据
  AudioAnalysis.createAudioAnalysis(audioEntity);

  // 可复用的视图对象，组件会在每一帧向其中写入数据
  const analysis: AudioAnalysisView = {
    amplitude: 0,
    bands: new Array<number>(8),
  };

  // 随音频振幅脉动的立方体
  const cube = engine.addEntity();
  MeshRenderer.setBox(cube);
  Transform.create(cube, { position: Vector3.create(8, 1, 8) });

  // 每一帧读取最新的分析值并缩放立方体
  engine.addSystem(() => {
    AudioAnalysis.readIntoView(audioEntity, analysis);
    const s = 1 + analysis.amplitude * 10;
    Transform.getMutable(cube).scale = Vector3.create(s, s, s);
  });
}
```

关键调用如下：

1. `AudioAnalysis.createAudioAnalysis(entity)` — 将组件附加到拥有 `AudioSource`, `AudioStream`或 `VideoPlayer`的实体上。默认使用对数模式（参见 [模式](#modes)).
2. `AudioAnalysis.readIntoView(entity, analysis)` — 将最新的 `amplitude` 和 8 个 `bands` 值复制到你提供的视图对象中。

{% hint style="warning" %}
**📔 注意**：调用 `bands` 之前，请务必预先分配包含 **8 个元素** 的数组。 `readIntoView`该组件不会为你调整数组大小。
{% endhint %}

## 逐帧读取数据

`AudioAnalysis` 设计为由系统每帧读取一次。建议采用以下模式：

1. 仅分配一次 `AudioAnalysisView` 对象。
2. 在系统中调用 `readIntoView` 以刷新它。
3. 直接使用这些值，或在多个系统之间共享此视图。

```ts
const analysis: AudioAnalysisView = {
  amplitude: 0,
  bands: new Array<number>(8),
};

engine.addSystem(() => {
  AudioAnalysis.readIntoView(audioEntity, analysis);
  // analysis.amplitude 和 analysis.bands[0..7] 现在包含最新值
});
```

如果被分析的实体可能尚未拥有 `AudioAnalysis` 组件（例如，该组件稍后才会创建或会被动态移除），请改用 `tryReadIntoView` 。如果组件不存在，它会返回 `false` ；如果已写入值，则返回 `true` 。

```ts
engine.addSystem(() => {
  if (!AudioAnalysis.tryReadIntoView(audioEntity, analysis)) return;
  // 此处可以安全地使用 analysis
});
```

{% hint style="info" %}
**💡 提示**：调用 `readIntoView` 一次，然后让多个系统共享同一个视图对象，这比反复读取组件更好。
{% endhint %}

## 对特定频段做出响应

这 8 个频段从低到高覆盖了可听频谱。 `bands[0]` 是最低频（低音），而 `bands[7]` 是最高频（高音）。你可以用不同频段驱动不同实体，构建经典的均衡器。

```ts
import {
  engine,
  Transform,
  MeshRenderer,
  材质，
  AudioSource,
  AudioAnalysis,
  AudioAnalysisView,
  模式，
} from "@dcl/sdk/ecs";
import { Color4, Vector3 } from "@dcl/sdk/math";

// 自定义组件，用于标记每个条形并记录其对应的频段
const VisualBar = engine.defineComponent("visual-bar", {
  index: Schemas.Number,
});

const BARS_HEIGHT = 12;

export function main() {
  const audioEntity = engine.addEntity();
  Transform.create(audioEntity);
  AudioSource.create(audioEntity, {
    audioClipUrl: "sounds/music.mp3",
    playing: true,
    loop: true,
  });
  AudioAnalysis.createAudioAnalysis(audioEntity);

  const analysis: AudioAnalysisView = {
    amplitude: 0,
    bands: new Array<number>(8),
  };

  // 创建 8 个条形，每个频段对应一个
  for (let i = 0; i < 8; i++) {
    const bar = engine.addEntity();
    VisualBar.create(bar, { index: i });
    Transform.create(bar, { position: Vector3.create(4 + i, 0, 8) });
    MeshRenderer.setBox(bar);
    Material.setPbrMaterial(bar, { albedoColor: Color4.Yellow() });
  }

  // 每帧读取一次
  engine.addSystem(() => {
    AudioAnalysis.readIntoView(audioEntity, analysis);
  });

  // 根据对应频段缩放每个条形
  engine.addSystem(() => {
    for (const [entity] of engine.getEntitiesWith(VisualBar, Transform)) {
      const index = VisualBar.get(entity).index;
      const transform = Transform.getMutable(entity);
      transform.scale = Vector3.create(
        1,
        analysis.bands[index] * BARS_HEIGHT,
        1
      );
    }
  });
}
```

这与 [音频可视化示例场景](https://github.com/decentraland/sdk7-test-scenes/tree/main/scenes/88,-10-audio-visualization)使用的是同一模式，只是精简到了核心内容。

## 模式

`AudioAnalysis` 支持两种分析模式，在创建组件时设置：

* `PBAudioAnalysisMode.MODE_LOGARITHMIC` （默认）：使用对数曲线缩放数值，更贴近人耳感知音量变化的方式。最适合用于视觉效果响应。
* `PBAudioAnalysisMode.MODE_RAW`：未经处理的振幅和 FFT 频段值。如果你想自行缩放数值，请使用此模式。

```ts
import { AudioAnalysis, PBAudioAnalysisMode } from "@dcl/sdk/ecs";

// 使用原始值
AudioAnalysis.createAudioAnalysis(audioEntity, PBAudioAnalysisMode.MODE_RAW);
```

### 调整对数模式

在对数模式下，你可以传入两个可选的增益乘数：

* `amplitudeGain` — 应用于整体振幅的乘数。默认值为 `5`.
* `bandsGain` — 应用于全部 8 个频段的乘数。默认值为 `0.05`.

较高的增益会让数值响应更明显；较低的增益则会让响应更轻微。

```ts
// 增强振幅响应，减弱频段响应
AudioAnalysis.createAudioAnalysis(
  audioEntity,
  PBAudioAnalysisMode.MODE_LOGARITHMIC,
  10, // amplitudeGain
  0.03 // bandsGain
);
```

{% hint style="warning" %}
**📔 注意**: `amplitudeGain` 和 `bandsGain` 仅在对数模式下生效。在原始模式下会被忽略。
{% endhint %}

## 替换现有组件

`createAudioAnalysis` 如果实体已经具有 `AudioAnalysis` 组件，则会失败。若要在运行时切换模式或增益，请使用 `createOrReplaceAudioAnalysis`，其签名相同。

```ts
// 在场景运行期间切换为原始模式
AudioAnalysis.createOrReplaceAudioAnalysis(
  audioEntity,
  PBAudioAnalysisMode.MODE_RAW
);
```

## 组件参考

### `AudioAnalysis.createAudioAnalysis(entity, mode?, amplitudeGain?, bandsGain?)`

将 `AudioAnalysis` 组件附加到 `entity`。如果该实体已具有此组件，则会失败。

* `entity` (`Entity`）：拥有以下对象的实体： `AudioSource`, `AudioStream`或 `VideoPlayer` 你想要分析的对象。
* `mode` (`PBAudioAnalysisMode`，可选）： `MODE_LOGARITHMIC` （默认值）或 `MODE_RAW`.
* `amplitudeGain` (`number`，可选）：对数模式下的振幅乘数。默认值为 `5`.
* `bandsGain` (`number`，可选）：对数模式下的频段乘数。默认值为 `0.05`.

### `AudioAnalysis.createOrReplaceAudioAnalysis(entity, mode?, amplitudeGain?, bandsGain?)`

与上述相同，但会替换现有的 `AudioAnalysis` 实体上的组件，而不是失败。

### `AudioAnalysis.readIntoView(entity, out)`

将最新值读取到 `out`。如果 `entity` 没有 `AudioAnalysis` 组件，则会抛出异常。

* `entity` (`Entity`）：带有该组件的实体。
* `out` (`AudioAnalysisView`）：由你提供的视图对象。必须预先分配好 `bands` ，其中包含 8 个数字。

### `AudioAnalysis.tryReadIntoView(entity, out): boolean`

与 `readIntoView`相同，但如果实体没有 `false` ，而不是抛出异常。成功写入值时返回 `AudioAnalysis` 组件，则返回 `true` 。

### `AudioAnalysisView`

你分配的普通对象，用于接收分析数据：

```ts
type AudioAnalysisView = {
  amplitude: number; // 整体信号强度
  bands: number[]; // 8 个频段，从低（0）到高（7）
};
```

## 注意事项和限制

* **固定为 8 个频段。** 频段数量固定为 8。没有可请求更多或更少频段的 API。
* **每个分析对象对应一个音频源。** 每个 `AudioAnalysis` 组件都会分析其所附着实体的音频。若要分析多个音源，请将 `AudioAnalysis` 附加到每个音源上。
* **视频音轨也会被分析。** `AudioAnalysis` 读取 [`VideoPlayer`](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/video-playing.md) 的音频，方式与读取 `AudioSource`相同，支持渐进式视频文件（如 `.mp4`）和实时 HLS 流（`.m3u8`）。将其附加 `AudioAnalysis` 到持有该组件的同一实体上 `VideoPlayer`.
* **音频暂停时不会报告更新。** 底层音频停止或暂停时，组件值也会停止变化。在音频再次播放之前，你最后读取的值会保留在视图对象中。
* **成本低，但并非免费。** 逐帧分析的开销很低（桌面设备上每个源不到一毫秒）。如果不需要这些数据，请避免同时将 `AudioAnalysis` 附加到多个源上。可视化效果不可见时，请移除该组件。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/audio-analysis.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
