> 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-es/escenas-sdk7/media/audio-streaming.md).

# Audio Streaming

Puedes hacer stream de audio desde una URL. Esto es útil para reproducir música directamente desde una radio por Internet, o para hacer stream de una conferencia en tu escena.

{% hint style="info" %}
**💡 Consejo**: En el [Scene Editor in Creator Hub](/creator/content-creator-es/scene-editor/empezar/about-editor.md), puedes usar un **Audio Stream** [Smart Item](/creator/content-creator-es/scene-editor/interactividad/smart-items.md) como una forma sin código de lograrlo.
{% endhint %}

El audio de la fuente debe estar en uno de los siguientes formatos: `.mp3`, `ogg`, o `aac`. La fuente también debe ser una *https* URL (*http* no se admiten URLs), y la fuente debe tener [políticas CORS (Cross Origin Resource Sharing)](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) que permitan acceder a ella externamente. Si no es así, puede que necesites configurar un servidor que actúe como proxy y exponga el stream de una forma válida.

{% hint style="warning" %}
**📔 Nota**: Para reproducir en su lugar un sonido pregrabado en tu escena, consulta [Sonidos](/creator/content-creator-es/escenas-sdk7/conceptos-basicos-de-contenido-3d/sounds.md).
{% endhint %}

Para añadir un stream de audio a tu escena, simplemente añade un `AudioStream` componente a una entidad:

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

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

{% hint style="warning" %}
**📔 Nota**El sonido del stream no es posicional; se oirá a un volumen constante en toda tu escena. Si un jugador sale de la escena, no oirá el stream en absoluto.
{% endhint %}

Establece el volumen del `AudioStream` componente cambiando su `volume` propiedad.

Activa o desactiva el `AudioStream` componente configurando su `playing` propiedad en *true* o *false*.

{% hint style="info" %}
**📔 Nota**: No todos los servicios de streaming te permiten reproducir su audio fuera de su sitio. Los siguientes son algunos ejemplos que funcionan en 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 %}

## Estado del stream

Consulta el estado de un stream de audio usando la función `AudioStream.getAudioState()`, pasando la entidad que posee el `AudioStream` componente.

El valor devuelto es un `PBAudioEvent` objeto (o `undefined` si el stream aún no ha informado de ningún estado), que contiene un `state` campo `timestamp` campo. El `state` campo es un valor del `MediaState` enum. Este enum tiene los siguientes valores posibles:

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

El siguiente ejemplo comprueba el estado de un stream y registra cuándo cambia.

```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('Estado del stream: ', currentState)
			lastState = currentState

			if (currentState == MediaState.MS_ERROR) {
				// Intentar reconexión
			}
		}
	})
}
```

## Audio espacial

De forma predeterminada, el audio de un `AudioStream` componente es global, lo que significa que se oirá a un volumen constante en toda tu escena. Si un jugador sale de la escena, no oirá el stream en absoluto.

Para hacer que el audio sea espacial, establece el `spatial` propiedad en *true*.

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

Ahora el audio se oirá desde la posición de la entidad que posee el `AudioStream` componente, y sonará más alto a medida que el jugador se acerque.

Controla el audio espacial con las siguientes propiedades:

* `spatialMinDistance`: La distancia mínima a la que el audio se vuelve espacial. Si el jugador está más cerca, el audio se oirá a volumen máximo. *0* de forma predeterminada.
* `spatialMaxDistance`: La distancia máxima a la que se oye el audio. Si el jugador está más lejos, el audio se oirá a volumen 0. *60* de forma predeterminada

```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" %}
**📔 Nota**: Algunos formatos de audio no admiten audio espacial. Asegúrate de que el audio del stream esté codificado en *mp3*, *AAC-LC* o *FLAC*.
{% endhint %}

## Análisis de audio

Puedes leer datos de amplitud y frecuencia en tiempo real de una `AudioStream` entidad para impulsar elementos visuales reactivos como ecualizadores o luces que pulsan al ritmo. Consulta [Análisis de audio](/creator/content-creator-es/escenas-sdk7/media/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 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-es/escenas-sdk7/media/audio-streaming.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.
