> 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-ko/sdk7/media/audio-analysis.md).

# 오디오 분석

씬에서 재생 중인 오디오의 실시간 진폭 및 주파수 데이터를 읽어 반응형 비주얼을 구동합니다.

이 `AudioAnalysis` 컴포넌트는 씬에서 재생 중인 오디오 소스의 실시간 데이터를 읽으므로, 음악에 맞춰 시각 효과를 연출할 수 있습니다. 매 프레임마다 전체 **진폭** 값과 **8개의 주파수 대역** (저음부터 고음까지)을 제공하며, 이를 사용해 엔티티의 크기, 색상 또는 애니메이션을 조정할 수 있습니다.

일반적인 활용 사례:

* 베이스에 맞춰 튀어 오르는 큐브.
* 박자에 맞춰 깜박이는 조명.
* 이퀄라이저 스타일의 막대 시각화.
* 음악에 맞춰 반응하는 머티리얼 또는 크기가 변하는 소품.

`AudioAnalysis` 는 읽기 전용 데이터 피드입니다. 씬은 값을 읽기만 하고, 런타임이 값을 채웁니다. 이 컴포넌트는 [AudioSource](/creator/content-creator-ko/sdk7/3d/sounds.md), [AudioStream](/creator/content-creator-ko/sdk7/media/audio-streaming.md)또는 [VideoPlayer](/creator/content-creator-ko/sdk7/media/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,
  Material,
  AudioSource,
  AudioAnalysis,
  AudioAnalysisView,
  Schemas,
} 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, // 진폭 게인
  0.03 // 밴드 게인
);
```

{% 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[]; // 저음(0)부터 고음(7)까지 8개 주파수 대역
};
```

## 참고 사항 및 제한 사항

* **대역은 8개로 고정됩니다.** 주파수 대역 수는 8개로 고정되어 있습니다. 대역 수를 늘리거나 줄이는 API는 없습니다.
* **분석당 오디오 소스 하나입니다.** 각 `AudioAnalysis` 컴포넌트는 자신이 연결된 엔티티의 오디오를 분석합니다. 여러 소스를 분석하려면 각 소스에 `AudioAnalysis` 를 연결합니다.
* **비디오 사운드트랙도 분석됩니다.** `AudioAnalysis` 는 다음의 오디오를 [`VideoPlayer`](/creator/content-creator-ko/sdk7/media/video-playing.md) 에서 읽는 것과 같은 방식으로 읽습니다. `AudioSource`에서와 마찬가지로, 프로그레시브 비디오 파일(예: `.mp4`)과 실시간 HLS 스트림(`.m3u8`). 연결하세요 `AudioAnalysis` 을(를) 보유한 동일한 엔터티에 `VideoPlayer`.
* **오디오가 일시 중지되면 업데이트가 보고되지 않습니다.** 기본 오디오가 중지되거나 일시 중지되면 컴포넌트 값의 변경이 멈춥니다. 마지막으로 읽은 값은 오디오가 다시 재생될 때까지 뷰 객체에 유지됩니다.
* **저렴하지만 무료는 아닙니다.** 프레임별 분석은 비용이 적게 들도록 설계되었습니다(데스크톱에서 소스당 1밀리초 미만). 데이터가 필요하지 않다면 여러 소스에 `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-ko/sdk7/media/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.
