> 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-streaming.md). Agents can also search and read this documentation through its [MCP server](https://docs.decentraland.org/~gitbook/mcp).

# 音频流

在场景中播放实时音频流。

你可以从 URL 流式传输音频。这适用于直接播放网络电台的音乐，或将会议直播到场景中。

{% hint style="info" %}
**💡 提示**：在 [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/jiao-hu-xing/smart-items.md) ，无需编写代码即可实现此功能。
{% endhint %}

源音频必须采用以下格式之一： `.mp3`, `ogg`或 `aac`。源还必须是 *https* URL（*http* URL 不受支持），并且源应配置允许外部访问的 [CORS 策略（跨源资源共享）](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) 。如果不满足这些条件，你可能需要设置一台服务器作为代理，以有效的方式公开此音频流。

{% hint style="warning" %}
**📔 注意**：若要在场景中播放预先录制的声音，请参阅 [声音](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md).
{% endhint %}

要在场景中添加音频流，只需向实体添加一个 `AudioStream` 组件：

```ts
const streamEntity = engine.addEntity()

AudioStream.create(streamEntity, {
	url: 'https://icecast.ravepartyradio.org/ravepartyradio-192.mp3',
	playing: true,
	volume: 0.8,
})
```

{% hint style="warning" %}
**📔 注意**：流式播放的声音没有空间定位效果；在整个场景中听到的音量始终一致。如果玩家走出场景，就完全听不到该音频流。
{% endhint %}

通过更改 `AudioStream` 组件的 `volume` 属性来设置其音量。

将 `AudioStream` 组件的 `playing` 属性设为 *true* 或 *false*.

{% hint style="info" %}
**📔 注意**：并非所有流媒体服务都允许在其网站之外播放音频。以下是一些在 Decentraland 中可用的示例：

```ts
DELTA = "https://cdn.instream.audio/:9069/stream?_=171cd6c2b6e"
GRAFFITI = "https://n07.radiojar.com/2qm1fc5kb.m4a?1617129761=&rj-tok=AAABeIR7VqwAilDFeUM39SDjmw&rj-ttl=5"
ISLA NEGRA = "https://radioislanegra.org/listen/up/basic.aac"
```

{% endhint %}

## 流状态

您可以通过以下任一方式监控音频流的状态： `audioEventsSystem` （基于回调，推荐），或通过轮询 `AudioStream.getAudioState()`.

### 使用 audioEventsSystem（推荐）

注册一个回调，仅当流状态发生变化时触发。这与 `AudioSource` 实体使用的系统相同（请参阅 [检测声音何时结束](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/3d-nei-rong-ji-chu/sounds.md#detect-when-a-sound-finishes)).

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

export function main() {
	const entity = engine.addEntity()

	AudioStream.create(entity, {
		playing: true,
		volume: 1,
		url: 'https://audio-edge-es6pf.mia.g.radiomast.io/ref-128k-mp3-stereo',
	})

	audioEventsSystem.registerAudioEventsEntity(entity, (event) => {
		console.log('Stream state: ', event.state)

		if (event.state === MediaState.MS_ERROR) {
			// 尝试重新连接
		}
	})
}
```

### 使用 getAudioState 进行轮询

您也可以使用 `AudioStream.getAudioState()`，在每一帧轮询流的状态。此方法会返回一个 `PBAudioEvent` 对象（如果尚未报告状态，则返回 `undefined` ），其中包含一个 `state` 字段和一个 `timestamp` 字段。该 `state` 字段的值属于 `MediaState` 枚举：

* `MS_NONE`
* `MS_LOADING`
* `MS_READY`
* `MS_PLAYING`
* `MS_PAUSED`
* `MS_BUFFERING`
* `MS_SEEKING`
* `MS_ERROR`

```ts
export function main() {
	const entity = engine.addEntity()

	AudioStream.create(entity, {
		playing: true,
		volume: 1,
		url: 'https://audio-edge-es6pf.mia.g.radiomast.io/ref-128k-mp3-stereo',
	})

	let lastState: MediaState | undefined = undefined
	engine.addSystem(() => {
		const currentState = AudioStream.getAudioState(entity)?.state
		if (lastState !== currentState) {
			console.log('Stream state: ', currentState)
			lastState = currentState

			if (currentState == MediaState.MS_ERROR) {
				// 尝试重新连接
			}
		}
	})
}
```

## 空间音频

默认情况下，来自 `AudioStream` 组件是全局的，这意味着在整个场景中听到的音量始终一致。如果玩家走出场景，就完全听不到流媒体音频。

若要启用空间音频，请将 `spatial` 属性设为 *true*.

```ts
AudioStream.create(entity, {
	url: 'https://radioislanegra.org/listen/up/stream',
    playing: true,
	spatial: true,
})
```

现在，音频将从拥有 `AudioStream` 组件的实体位置播放，玩家越靠近，声音就越大。

可通过以下属性控制空间音频：

* `spatialMinDistance`：音频开始呈现空间效果的最小距离。如果玩家距离更近，音频将以最大音量播放。 *0* （默认值）。
* `spatialMaxDistance`：音频可听到的最大距离。如果玩家距离更远，音量将为 0。 *60* （默认值）

```ts
const audioStreamEntity = engine.addEntity();

Transform.create(audioStreamEntity, {
    position: Vector3.create(8, 0, 8),
});

AudioStream.create(audioStreamEntity, {
    url: 'https://radioislanegra.org/listen/up/stream',
    playing: true,
    volume: 1.0,
    spatial: true,
    spatialMinDistance: 5,
    spatialMaxDistance: 10
});
```

{% hint style="warning" %}
**📔 注意**：某些音频格式不支持空间音频。请确保流媒体音频采用以下格式编码： *mp3*, *AAC-LC* 或 *FLAC*.
{% endhint %}

## 音频分析

你可以从一个 `AudioStream` 实体读取实时振幅和频率数据，以驱动均衡器或随节拍闪烁的灯光等响应式视觉效果。请参阅 [音频分析](https://docs.decentraland.org/creator/content-creator-zh/chang-jing-sdk7/mei-ti/audio-analysis.md).


---

# 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-streaming.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.
