> 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/3d-nei-rong-ji-chu/sounds.md).

# 声音

了解如何向场景中添加声音。

声音是为玩家的操作和事件提供反馈的绝佳方式。背景音效还能为场景增添更多背景信息，提升玩家的沉浸感。

{% hint style="warning" %}
**📔 注意**：请注意，只有站在构成声音生成场景的地块内的玩家才能听到声音，即使其他玩家处于声音的可听范围内也是如此。玩家也可以在设置中关闭所有声音。
{% endhint %}

支持的音频格式因浏览器而异，但建议使用 *.mp3*.

*.wav* 格式也受支持，但通常不建议使用，因为文件体积明显更大。

## 播放声音

播放声音最简单的方法是在 **音频源** 组件添加到 [Creator Hub 中的场景编辑器](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/ru-men/about-editor.md) 中，并将其设置为 **开始播放** 和 **循环**。请参阅 [添加组件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-bian-ji-qi/gou-jian/components.md#add-components).

![](https://2460066822-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-zh/chang-jing-bian-ji-qi/jiao-hu-xing/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`，包括全局声音。没有它，声音不会播放，也不会记录错误，因此很难发现这个问题。放置在场景编辑器中的物品始终带有一个 `Transform`，所以这只会影响你在代码中创建的实体。
{% endhint %}

声音文件必须位于项目文件夹内。在上面的示例中，音频文件位于 `assets/sounds` 文件夹中，该文件夹位于场景项目文件夹的根目录。

{% hint style="warning" %}
**📔 注意**： `AudioSource` 组件必须通过以下语句导入：

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

有关如何轻松处理这些内容，请参阅 [导入](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/ru-men/coding-scenes.md#imports) 。
{% endhint %}

AudioSource.playSound() `函数` 接受以下参数：

* `entity`：要将声音应用到的实体。声音会从该实体的位置传出，也就是说，玩家越靠近它，声音就越大。
* `src`：项目中声音文件的位置。

{% hint style="info" %}
**💡 提示**：为了让结构更清晰，我们建议将声音文件单独存放在场景中的 `assets/sounds` 文件夹内。
{% endhint %}

* `resetCursor`: *（可选）* 如果为 true，声音始终从头开始播放；否则会从当前播放位置继续。适用于暂停和恢复播放。

`playSound()` 会在实体尚未包含 `AudioSource` 组件时创建该组件。如果实体已经包含该组件， `playSound()` 则会保留其其他值，例如 `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，声音便会开始播放。你可以将 `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-zh/chang-jing-sdk7/you-hua/pre-load-resources.md) 文档。

## 停止声音

若要停止实体播放声音，请使用 `AudioSource.stopSound()` 函数。只需指定实体即可，因为每个实体都只有一个 `AudioSource` 组件，并且每个 `AudioSource` 组件一次只播放一个文件。

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

`stopSound()` 在实体没有 `false` AudioSource `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 `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()` 会导致组件在每一帧都被标记为已更改，从而产生不必要的同步开销。

&#x20;`playing`  属性仅在声音自行播放结束时由引擎切换。如果场景显式停止声音（通过 `AudioSource.stopSound()` 或将 `playing` 设置为 *false*），则该更改来自你自己的代码；循环播放的声音会一直播放，直到被停止，因此属性不会自行切换。
{% endhint %}

另一种方法是使用 `audioEventsSystem.registerAudioEventsEntity` 定义一个函数，每当实体音频的播放状态发生变化时就会运行，就像视频的 [事件](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/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-zh/chang-jing-sdk7/mei-ti/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-zh/chang-jing-sdk7/mei-ti/audio-streaming.md) 了解如何从外部来源播放实时音频流。

## 音频分析

请参阅 [音频分析](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/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-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/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.
