> 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/3d/sounds.md).

# 사운드

씬에 사운드를 추가하는 방법을 알아보세요.

사운드는 플레이어의 행동과 이벤트에 피드백을 제공하는 훌륭한 방법이며, 배경음은 씬에 더 많은 맥락을 부여하고 플레이어의 몰입감을 높일 수도 있습니다.

{% hint style="warning" %}
**📔 참고**: 사운드는 생성된 씬을 구성하는 parcel 안에 서 있는 플레이어만 들을 수 있다는 점을 기억하세요. 원래는 청취 범위 안에 있더라도 마찬가지입니다. 플레이어는 설정에서 모든 사운드를 끌 수도 있습니다.
{% endhint %}

지원되는 사운드 형식은 브라우저에 따라 다르지만, 사용하는 것이 권장됩니다 *.mp3*.

*.wav* 파일도 지원되지만, 훨씬 더 무겁기 때문에 일반적으로는 권장되지 않습니다.

## 사운드 재생

사운드를 재생하는 가장 쉬운 방법은 다음을 추가하는 것입니다. **Audio Source** 컴포넌트를 시각적으로 다음에 [Creator Hub의 Scene Editor](/creator/content-creator-ko/scene-editor/get-started/about-editor.md) 그리고 이를 다음으로 설정한 뒤 **재생 시작** 및 **루프**. 자세한 내용은 [컴포넌트 추가](/creator/content-creator-ko/scene-editor/build/components.md#add-components).

![](https://3980763956-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoPnXBby9S6MrsW83Y9qZ%2Fuploads%2Fgit-blob-ae588633ad20c357cfcb71a63216e4b8e02802ae%2FAudioSource-component.png?alt=media)

코드 없이 다음을 통해 사운드 재생을 트리거할 수도 있습니다 **동작**, 자세한 내용은 [어떤 항목이든 스마트 아이템으로 만들기](/creator/content-creator-ko/scene-editor/interactivity/make-any-item-smart.md).

코드로 사운드를 재생하려면 다음을 사용하세요 `AudioSource.playSound` 함수를 실행 중이라고 가정합니다.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()

// 사운드 재생
AudioSource.playSound(sourceEntity, 'assets/sounds/sound-effect.mp3')
```

사운드 파일은 프로젝트 폴더 안에 있어야 합니다. 위 예시에서는 오디오 파일이 다음 위치에 있습니다. `assets/sounds` 폴더이며, 씬 프로젝트 폴더의 루트 수준에 위치합니다.

{% hint style="warning" %}
**📔 참고**:  `AudioSource` 컴포넌트는 다음을 통해 임포트해야 합니다

> `import { AudioSource } from "@dcl/sdk/ecs"`

참고 [가져오기](/creator/content-creator-ko/sdk7/getting-started/coding-scenes.md#imports) 를 사용하면 이를 쉽게 처리할 수 있습니다.
{% endhint %}

그 `AudioSource.playSound()` 함수는 다음 인수를 받습니다:

* `entity`: 사운드를 적용할 엔티티입니다. 사운드는 해당 엔티티의 위치에서 들리며, 플레이어가 가까워질수록 더 크게 들립니다.
* `src`: 프로젝트 내 사운드 파일의 위치입니다.

{% hint style="info" %}
**💡 팁**: 더 명확하게 관리하려면 사운드 파일을 별도의 `assets/sounds` 폴더로 씬 내부에 분리해 두는 것을 권장합니다.
{% endhint %}

* `resetCursor`: *(선택 사항)* true이면 사운드는 항상 처음부터 시작합니다. 그렇지 않으면 현재 커서 위치에서 계속됩니다. 일시 정지 및 재개에 유용합니다.

사운드를 재생하는 또 다른 방법은 엔티티에 `AudioSource` 컴포넌트를 수동으로 생성하는 것입니다. 이 방법을 사용하면 사운드를 더 세밀하게 제어할 수 있습니다. 예를 들어 반복 재생하거나 볼륨을 설정할 수 있습니다.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()

// AudioSource 컴포넌트 생성
AudioSource.create(sourceEntity, {
	audioClipUrl: 'sounds/sound-effect.mp3',
	loop: true,
	playing: true,
})
```

다음 속성을 설정할 수 있습니다:

* `audioClipUrl`: 프로젝트 내 사운드 파일의 위치입니다.
* `playing`: true이면 사운드가 재생을 시작합니다. 사운드를 `playing` false로 설정한 뒤 나중에 true로 바꿀 수 있습니다.
* `volume`: *(선택 사항)* 사운드 파일의 볼륨입니다. 기본값은 1이며, 최대 볼륨입니다.
* `pitch`: *(선택 사항)* 사운드의 피치를 변경합니다. 기본값은 1이며, 더 낮게 설정하면 더 낮은 음의 소리가 되고 더 높게 설정하면 더 높은 음의 소리가 됩니다.

{% hint style="info" %}
**💡 팁**: 게임 중 사운드 효과가 너무 반복적으로 들리지 않도록 하려면, 재생될 때마다 사운드의 피치를 약간씩 무작위로 바꾸는 것이 유용합니다.
{% endhint %}

* `currentTime`: *(선택 사항)* 기본값은 0입니다. 사운드 파일의 시작부터 재생되지 않도록 하려면 이 값을 설정하세요.

각 엔티티는 단 하나의 `AudioSource` 컴포넌트만 가질 수 있으며, 한 번에 하나의 클립만 재생할 수 있습니다. 이 제한은 새 사운드를 재생할 때 오디오 소스를 수정하거나, 각자 고유한 사운드를 가진 여러 개의 보이지 않는 자식 엔티티를 포함함으로써 쉽게 극복할 수 있습니다.

{% hint style="warning" %}
**📔 참고**: 사운드는 각 플레이어의 로컬 인스턴스에서 재생됩니다. 주변의 다른 플레이어는 자신의 로컬 씬에서도 명시적으로 재생하지 않는 한 같은 사운드를 듣지 못합니다.
{% endhint %}

### 사운드 미리 로드

엔티티가 사운드를 사용하지만 씬 실행 시 즉시 재생되지 않는다면, 다운로드에 시간이 걸릴 수 있습니다. 다음을 사용하면 씬 실행 시 사용할 수 있게 할 수 있습니다. `AssetLoad` 컴포넌트를 부여해야 합니다.

```ts
import { AssetLoad } from "@dcl/sdk/ecs"

AssetLoad.create(engine.RootEntity, {
  assets: [
    "assets/scene/bundle1/explosionSound.mp3",
  ],
})
```

자세한 내용은 다음을 확인하세요 [리소스 미리 로드](/creator/content-creator-ko/sdk7/optimizing/pre-load-resources.md) 문서를 확인하세요.

## 사운드 중지

엔티티의 사운드 재생을 중지하려면 다음을 사용하세요 `AudioSource.stopSound()` 함수입니다. 각 엔티티는 단 하나의 `AudioSource` 컴포넌트만 가지며, 각 `AudioSource` 컴포넌트는 한 번에 하나의 파일만 재생하기 때문입니다.

```ts
AudioSource.stopSound(sourceEntity)
```

사운드를 중지하는 또 다른 방법은 다음의 `playing` 속성을 false로 설정하는 것입니다.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()

// AudioSource 컴포넌트 생성
AudioSource.create(sourceEntity, {
	audioClipUrl: 'sounds/explosion.mp3',
	playing: true,
})

// 간단한 함수 정의
function stopSound(entity: Entity) {
	// 오디오 소스 컴포넌트의 mutable 버전 가져오기
	const audioSource = AudioSource.getMutable(entity)

	// playing 값을 수정
	audioSource.playing = false
}

// 함수 호출
stopSound(sourceEntity)
```

## 사운드가 끝났는지 감지

루프하지 않는 사운드가 스스로 재생을 끝내면, 엔진은 다음의 `playing` 속성을 `AudioSource` 컴포넌트의 값을 다시 *false*로 변경합니다. 씬의 코드는 이 값을 읽어 사운드가 언제 끝났는지 알 수 있으며, 예를 들어 바로 뒤에 다른 사운드나 동작을 연결할 수 있습니다.

```ts
let wasPlaying = false

engine.addSystem(() => {
	const audio = AudioSource.get(sourceEntity)
	const isPlaying = audio.playing ?? false

	if (wasPlaying && !isPlaying) {
		console.log('sound finished playing')
		// 여기서 반응: 다른 사운드 재생, 시퀀스 진행 등
	}

	wasPlaying = isPlaying
})
```

{% hint style="warning" %}
**📔 참고**: 매 프레임 컴포넌트를 폴링할 때는 항상 다음으로 읽으세요 `AudioSource.get()` (읽기 전용). 다음을 사용하면 `AudioSource.getMutable()` 매 프레임마다 컴포넌트가 변경된 것으로 표시되어 불필요한 동기화 작업이 발생합니다.

그 `playing` 속성은 사운드가 스스로 끝날 때만 엔진에 의해 변경됩니다. 씬이 사운드를 명시적으로 중지하면(다음을 통해 `AudioSource.stopSound()` 또는 다음을 설정하여 `playing` 를 *false*), 그 변경은 여러분의 코드에서 발생한 것이며, 루프 사운드는 중지될 때까지 재생되므로 스스로는 절대 이 속성을 변경하지 않습니다.
{% endhint %}

대신 다음을 사용하세요 `audioEventsSystem.registerAudioEventsEntity` 엔티티의 오디오 재생 상태가 변경될 때마다 실행되는 함수를 정의합니다. 이는 다음과 같습니다. [비디오 이벤트](/creator/content-creator-ko/sdk7/media/video-playing.md#video-events) 동영상용입니다. 함수는 다음을 포함한 이벤트를 받습니다. `state` 필드이며, 다음을 사용합니다. `MediaState` 열거형입니다.

```ts
import { engine, AudioSource, audioEventsSystem, MediaState } from '@dcl/sdk/ecs'

// ... AudioSource 컴포넌트가 있는 sourceEntity 생성 ...

audioEventsSystem.registerAudioEventsEntity(sourceEntity, (audioEvent) => {
	switch (audioEvent.state) {
		case MediaState.MS_LOADING:
			console.log('audio event - sound is LOADING')
			break
		case MediaState.MS_READY:
			console.log('audio event - sound is READY (loaded, or finished playing)')
			break
		case MediaState.MS_PLAYING:
			console.log('audio event - sound started PLAYING')
			break
		case MediaState.MS_ERROR:
			console.log('audio event - sound ERROR (e.g. the file failed to load)')
			break
	}
})
```

다음에서 `MS_PLAYING` 를 `MS_READY` 로의 전환은 사운드 재생이 중지되었음을 의미합니다. 전체 `MediaState` 열거형에는 다음도 포함됩니다. `MS_NONE`, `MS_LOADING`, `MS_PAUSED`, `MS_BUFFERING`, `MS_SEEKING` 및 `MS_ERROR`이며, 각 이벤트에는 `타임스탬프` 상태 변경이 발생한 시점의 타임스탬프가 포함됩니다. 또한 언제든지 다음으로 최신 보고 상태를 조회할 수 있습니다. `audioEventsSystem.getAudioState(entity)`, 다음으로 콜백 등록을 해제하세요 `audioEventsSystem.removeAudioEventsEntity(entity)`, 또는 엔티티가 등록되어 있는지 다음으로 확인하세요 `audioEventsSystem.hasAudioEventsEntity(entity)`. 같은 시스템은 다음이 있는 엔티티에도 작동합니다. [`AudioStream`](/creator/content-creator-ko/sdk7/media/audio-streaming.md) 컴포넌트를 부여해야 합니다.

{% hint style="warning" %}
**📔 참고**: 이 기능은 데스크톱 클라이언트에서만 지원됩니다.
{% endhint %}

## 루프 재생

사운드를 연속 루프로 계속 재생하려면 다음의 `loop` 필드를 `AudioSource` 컴포넌트에서 *true* 재생을 시작하기 전에 다음으로 설정하세요.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()

// AudioSource 컴포넌트 생성
AudioSource.create(sourceEntity, {
	audioClipUrl: 'sounds/sound-effect.mp3',
	playing: true,
	loop: true,
})
```

루프 사운드는 배경 음악이나 다른 배경음을 추가할 때 특히 유용합니다.

## 볼륨 설정

다음을 설정하여 `volume` 속성을 `AudioSource` 컴포넌트의 볼륨을 변경할 수 있습니다.

볼륨은 다음 범위의 숫자로 표현됩니다. *0* 를 *1*.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()

// AudioSource 컴포넌트 생성
AudioSource.create(sourceEntity, {
	audioClipUrl: 'sounds/sound-effect.mp3',
	playing: true,
	volume: 0.5,
})
```

{% hint style="warning" %}
**📔 참고**: 물론 사운드의 볼륨은 플레이어와 오디오 소스 사이의 거리에도 영향을 받습니다. 플레이어가 멀어질수록 볼륨은 더 낮아집니다.
{% endhint %}

## 전역 사운드

기본적으로 다음에서 발생하는 모든 사운드는 `AudioSource` 위치 기반입니다. 즉, 사운드가 다음의 위치에서 발생하는 것처럼 들립니다. `Transform` 컴포넌트이며, 플레이어가 가까이 갈수록 더 크게 들립니다. 하지만 사운드를 전역으로 설정해 플레이어가 어디에 서 있든 볼륨이 일정하게 유지되도록 할 수도 있습니다. 이는 배경 음악, 알림음 및 기타 비위치 기반 사운드에 이상적입니다.

{% hint style="warning" %}
**📔 참고**: 전역 사운드는 DCL 2.0 데스크톱 클라이언트에서만 지원되는 기능입니다.
{% endhint %}

사운드를 전역으로 만들려면 다음을 `global` 속성을 *true*.

```ts
AudioSource.create(sourceEntity, {
	audioClipUrl: 'sounds/music.mp3',
	playing: true,
	global: true,
})
```

## 사운드의 일부 재생

더 긴 사운드 파일의 일부를 재생하려면 다음을 사용하세요. `playSoundSegment()` SDK Utils 라이브러리의. 자세한 내용은 [SDK7 Utils](https://github.com/decentraland/sdk7-utils).

또한 다음을 명시적으로 설정하여 이를 달성할 수도 있습니다. `currentTime` 다음의 속성을 `AudioSource` 컴포넌트에 설정한 뒤, 일정 시간이 지난 후 중지하는 것입니다.

## 오디오 스트리밍

참고 [오디오 스트리밍](/creator/content-creator-ko/sdk7/media/audio-streaming.md) 외부 소스에서 라이브 오디오 스트림을 재생하는 방법을 알아보세요.

## 오디오 분석

참고 [오디오 분석](/creator/content-creator-ko/sdk7/media/audio-analysis.md) 다음에서 실시간 진폭 및 주파수 데이터를 읽는 방법을 알아보세요. `AudioSource` 그리고 이를 바탕으로 베이스에 맞춰 펄스하는 큐브나 이퀄라이저 스타일의 막대 시각화처럼 반응형 비주얼을 구현하세요.


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.decentraland.org/creator/content-creator-ko/sdk7/3d/sounds.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
