> 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" %}
**📔 참고**: 사운드가 생성된 씬을 구성하는 구획 안에 있는 플레이어만 사운드를 들을 수 있다는 점에 유의하세요. 듣는 거리 안에 있더라도 해당 구획 안에 있지 않으면 들을 수 없습니다. 플레이어는 설정에서 모든 사운드를 끌 수도 있습니다.
{% endhint %}

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

*.wav*  형식의 파일도 지원되지만, 용량이 훨씬 커서 일반적으로 권장하지 않습니다.

## 사운드 재생

사운드를 재생하는 가장 쉬운 방법은 다음 항목을 추가하는 것입니다. **오디오 소스** 컴포넌트를 시각적으로 [Creator Hub의 Scene Editor에서](https://docs.decentraland.org/creator/content-creator-ko/scene-editor/get-started/about-editor.md) 로 설정하고 **재생 시작** 및 **반복**. 자세한 내용은 [컴포넌트 추가](https://docs.decentraland.org/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-cf1d382199d0518859ab3a850b5a34b869e334f6%2FAudioSource-component.webp?alt=media)

코드 없이도 다음을 통해 사운드 재생을 트리거할 수 있습니다. **액션**, 참조 [어떤 항목이든 스마트하게 만들기](https://docs.decentraland.org/creator/content-creator-ko/scene-editor/interactivity/make-any-item-smart.md).

코드에서 사운드를 재생하려면 다음을 사용하세요. `AudioSource.playSound` 함수.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()
Transform.create(sourceEntity, { position: Vector3.create(8, 1, 8) })

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

{% hint style="warning" %}
**📔 참고**다음이 있는 모든 엔터티에는 `AudioSource` 도 필요합니다. `Transform`, 전역 사운드도 포함됩니다. 이것이 없으면 아무것도 재생되지 않고 오류도 기록되지 않아 문제를 발견하기 어렵습니다. Scene Editor에서 배치한 항목에는 항상 `Transform`이 있으므로, 이 문제는 코드에서 생성한 엔터티에만 영향을 미칩니다.
{% endhint %}

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

{% hint style="warning" %}
**📔 참고**:  `AudioSource` 구성 요소는 다음을 통해 가져와야 합니다

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

자세한 내용은 [가져오기](https://docs.decentraland.org/creator/content-creator-ko/sdk7/getting-started/coding-scenes.md#imports) 에서 쉽게 처리하는 방법을 확인하세요.
{% endhint %}

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

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

{% hint style="info" %}
**💡 팁**: 더 명확하게 관리하려면 사운드 파일을 별도의 `assets/sounds` 폴더에 보관하는 것이 좋습니다.
{% endhint %}

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

`playSound()` 엔티티에 아직 `AudioSource` 컴포넌트가 없으면 생성합니다. 이미 컴포넌트가 있으면 `playSound()` volume `volume`, `pitch`, `loop` 및 `global`, 같은 다른 값은 그대로 유지하므로, 사운드를 재생할 때마다 `playSound()` 를 호출하면 됩니다. 같은 파일로 다시 호출하면 사운드가 다시 재생됩니다. 항상 `true`.

사운드를 재생하는 또 다른 방법은 엔티티에 `AudioSource` 컴포넌트를 직접 생성하는 것입니다. 사운드 반복 재생이나 볼륨 설정 등 사운드를 더 세밀하게 제어하려면 이 방법을 사용하세요.

```ts
// 엔티티 생성
const sourceEntity = engine.addEntity()
Transform.create(sourceEntity, { position: Vector3.create(8, 1, 8) })

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

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

* `audioClipUrl`: 프로젝트 내 사운드 파일의 위치입니다.
* `playing`: true이면 사운드 재생을 시작합니다. 값을 false로 설정하여 사운드를 생성한 다음, 나중에 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",
  ],
})
```

자세한 내용은 [리소스 미리 로드하기](https://docs.decentraland.org/creator/content-creator-ko/sdk7/optimizing/pre-load-resources.md) 문서를 참조하세요.

## 사운드 중지하기

엔티티의 사운드 재생을 중지하려면 `AudioSource.stopSound()` 함수를 사용하세요. 각 엔티티에는 `AudioSource` 컴포넌트가 하나만 있고 각 `AudioSource` 컴포넌트는 한 번에 하나의 파일만 재생하므로 엔티티만 지정하면 됩니다.

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

`stopSound()` 는 엔티티에 `false` AudioSource `컴포넌트가 없으면` 를 반환합니다.

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

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

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

// 간단한 함수 정의
function stopSound(entity: Entity) {
	// 오디오 소스 컴포넌트의 변경 가능한 버전 가져오기
	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` 엔티티의 오디오 재생 상태가 변경될 때마다 실행되는 함수를 정의하려면, [비디오 이벤트](https://docs.decentraland.org/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`이며, 각 이벤트에는 상태 변경이 발생한 시점을 나타내는 `timestamp` 이 포함됩니다. 언제든지 다음을 사용해 마지막으로 보고된 상태를 확인할 수도 있습니다. `audioEventsSystem.getAudioState(entity)`다음으로 콜백 등록을 해제하거나 `audioEventsSystem.removeAudioEventsEntity(entity)`다음으로 엔티티가 등록되어 있는지 확인할 수 있습니다. `audioEventsSystem.hasAudioEventsEntity(entity)`입니다. 이 시스템은 [`AudioStream`](https://docs.decentraland.org/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,
})
```

전역 사운드도 해당 엔티티에 `Transform` 이 있어야 합니다. 위치가 더 이상 플레이어가 듣는 소리에 영향을 주지 않더라도 마찬가지입니다. 위치는 어디든 상관없습니다.

## 사운드의 일부 구간 재생하기

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

또는 `currentTime` 속성을 `AudioSource` 컴포넌트에 직접 설정한 다음 일정 시간 후 재생을 중지할 수도 있습니다.

## 오디오 스트리밍

외부 소스의 실시간 오디오 스트림을 재생하는 방법은 [오디오 스트리밍](https://docs.decentraland.org/creator/content-creator-ko/sdk7/media/audio-streaming.md) 에서 알아보세요.

## 오디오 분석

실시간 진폭 및 주파수 데이터를 [오디오 분석](https://docs.decentraland.org/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 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/3d/sounds.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.
