Live streams
Updated
A live stream is video or sound that is produced while the scene runs: a webcam, a microphone, a shared screen, or frames a script generates. Streams publishes live streams under a name, and a Media Stream component on an Audio, Positional Audio, Video or UI Video entity plays the stream with that name in place of the entity’s file. Streams.room goes one step further and shares your microphone, camera or screen with the people in the room, so a video call can happen inside the world.
Before you start
Section titled “Before you start”- You know the Audio and Video entities and the Media Stream component that plays a stream through them. See Media and text and Audio.
- You know
Input.camera,Input.microphoneandInput.screen, which start the device captures. See Input and interaction. - You know what a room is. See the Multiplayer overview.
Named streams
Section titled “Named streams”A named stream is a stream published under an id, such as 'sim' or 'me/camera'. Any entity in the scene whose Media Stream names that id plays it. The Media Stream’s stream prop is the id; while nothing is published under it, the entity waits, and disabling or removing the Media Stream returns the entity to its own file.
| Member | What it does |
|---|---|
Streams. |
Make a stream from data and publish it under id. video is { width, height }, audio is { sample; give one or both. Returns a writer. |
Streams. |
Publish an existing stream under id, such as Input.. Returns a function that unpublishes it. |
Streams.ids() |
The ids published now, by anyone. |
Streams. |
Whether something is published under id now. |
Streams. |
Call listener(live) right away and each time a stream is published under id (true) or goes (false). Returns a function that stops it. |
The writer that create returns has:
| Member | What it does |
|---|---|
write |
Send one video frame: RGBA pixels at the stream’s size (a Uint8), an ImageData, or a canvas or image drawn to fill it. |
write |
Send one chunk of interleaved sound samples, a Float32Array (-1 to 1) or an Int16Array, played live. |
close() |
Unpublish the stream and stop it. |
- Following a device. A stream from
Input.camera.stream()orInput.microphone.stream()keeps following its device: it is published again when the device switches or restarts, and unpublished when it stops. - Ownership. A script may only replace or unpublish the ids it published. What a script published, the streams it made and what it follows all go when the script is released.
The Media Stream component reports what it plays through its entity’s Signal Emitter:
| Event | Data | When |
|---|---|---|
Media |
{ stream } |
A live stream started playing through the entity. |
Media |
{ stream } |
It stopped. |
Sharing with the room
Section titled “Sharing with the room”Named streams play on this device. To let the people in the room see and hear you, publish your capture to the room with Streams.room. Room media is optional: an experience may not offer it, and state.status then says 'disabled' or 'unconfigured'.
| Member | What it does |
|---|---|
Streams. |
The room media state (see below). |
Streams. |
Join the room’s media. Resolves true once connected. It never opens a camera or microphone. |
Streams. |
Leave the room’s media. |
Streams. |
Call listener(state) right away and on each change. Returns a function that stops it; it also stops when the script is released. |
Streams. |
Share a capture this script has already started: 'mic', 'camera' or 'screen'. Resolves true once shared. |
Streams. |
Stop sharing it. The capture itself, and any local preview, keep running. |
The state has:
| Field | What it is |
|---|---|
status |
'disabled', 'unconfigured', 'idle', 'connecting', 'connected', 'disconnected', 'failed' or 'disposed'. |
room |
The room’s name, when there is one. |
publications |
What people in the room share: each with id, peerId, source ('mic', 'camera' or 'screen'), kind ('audio' or 'video'), paused and available. |
error |
A short description of the last problem, if any. |
A publication’s id is the stream id that plays it: set it as a Media Stream’s stream to show someone’s camera on a screen in the world. The media peer id in peerId is not the same as Network.peerId.
Examples
Section titled “Examples”1. A generated video feed
Section titled “1. A generated video feed”#pragma lifecycle(startup, update)
const WIDTH = 64;const HEIGHT = 36;const pixels = new Uint8ClampedArray(WIDTH * HEIGHT * 4);let feed;
function startup() { feed = Streams.create('plasma', { video: { width: WIDTH, height: HEIGHT } });}
function update(dt, time) { for (let y = 0; y < HEIGHT; y++) { for (let x = 0; x < WIDTH; x++) { const i = (y * WIDTH + x) * 4; const v = Math.sin(x * 0.2 + time) + Math.sin(y * 0.3 - time * 1.3); pixels[i] = 128 + 127 * Math.sin(v); pixels[i + 1] = 128 + 127 * Math.cos(v); pixels[i + 2] = 200; pixels[i + 3] = 255; } } feed.writeVideoFrame(pixels);}A script publishes a named stream with Streams.create and writes a plasma frame into it every update; the screen's Media Stream plays it.
Watch the screen. Drag to orbit the camera, scroll to zoom.
createpublishes the stream under'plasma', and the Screen’s Media Stream starts playing it.- One frame is written per
update; the pixel array is reused instead of allocated each frame. - The stream is closed automatically when the script is released.
2. A webcam mirror
Section titled “2. A webcam mirror”#pragma lifecycle(startup)
// Scene: a "Start Camera" UI Button with a Signal Emitter on 'mirror/start', and a// Video entity "Mirror" with a Media Stream on 'me/camera' and a Signal Emitter on 'mirror'.let unpublish;
function startup() { on('mirror', (event) => { if (event.eventType === EventType.MediaStream.Connected) log('Mirror is live'); if (event.eventType === EventType.MediaStream.Disconnected) log('Mirror stopped'); });
on('mirror/start', async (event) => { if (event.eventType !== EventType.UIButton.Press) return; if (unpublish) { unpublish(); unpublish = undefined; Input.camera.stop(); return; } if (!(await Input.camera.start())) { log('No camera, or permission refused'); return; } unpublish = Streams.publish('me/camera', Input.camera.stream()); });}Start camera publishes your camera as the stream me/camera, which a Video entity with a Media Stream plays; pressing again unpublishes it and stops the camera.
Press Start camera and allow the camera to see yourself on the screen; press it again to stop. Needs a camera and your permission.
- The camera starts from a button press, so the browser can ask for permission.
publishreturns the function that unpublishes; pressing again turns the mirror off.- The Media Stream events confirm when the Video entity starts and stops showing the camera.
Snippets
Section titled “Snippets”1. Talking to the room
Section titled “1. Talking to the room”#pragma lifecycle(startup)
// Scene: a "Mic" UI Toggle Button with a Signal Emitter on 'voice/mic'.let toggle;
function startup() { toggle = findEntity('Mic').getComponent(UIToggleButtonComponent);
Streams.room.subscribe((state) => { const mine = state.publications.filter((p) => p.source === 'mic'); log(`Room media ${state.status}, ${mine.length} microphones shared`); });
on('voice/mic', async (event) => { if (event.eventType !== EventType.UIToggleButton.Change) return; if (!event.data.checked) { await Streams.room.unpublish('mic'); Input.microphone.stop(); return; } const ready = (await Streams.room.connect()) && (await Input.microphone.start()) && (await Streams.room.publish('mic')); if (!ready) { log('Could not share the microphone:', Streams.room.state.error ?? Streams.room.state.status); toggle.setChecked(false); } });}- Three steps, each awaited: join the room’s media, start the microphone, then share it.
- If any step fails, the toggle is switched back off and the reason is logged.
- Turning the toggle off stops sharing and then stops the microphone.
2. Showing someone’s camera on a screen
Section titled “2. Showing someone’s camera on a screen”#pragma lifecycle(startup)
// Scene: a Video entity named "Wall Screen" with a Media Stream component.let media;let showing = '';
function startup() { media = findEntity('Wall Screen').getComponent(MediaStreamComponent);
Streams.room.subscribe((state) => { const camera = state.publications.find( (p) => p.source === 'camera' && p.kind === 'video' && p.available && !p.paused, ); const id = camera ? camera.id : ''; if (id === showing) return; showing = id; media.setProps({ stream: id }); log(camera ? `Showing ${camera.peerId}'s camera` : 'No camera to show'); });
Streams.room.connect();}- Each time the room’s publications change, the script picks the first available camera.
- Setting the Media Stream’s
streamto the publication’sidplays that camera on the wall; an empty id shows nothing live. showingavoids resetting the screen when nothing relevant changed.
Common mistakes
Section titled “Common mistakes”- Publishing before the device starts.
Input.camera.stream()isnulluntilInput.camera.start()resolvestrue. - Starting devices without a gesture. Browsers ask for camera, microphone and screen permission only after a click or key press. Start captures from a button.
- Expecting named streams to reach others.
Streams.publishandStreams.createplay on this device. UseStreams.room.publishto share with the room. - Confusing peer ids. A publication’s
peerIdis its media peer, notNetwork.peerId. - Allocating per frame. Reuse the pixel and sample arrays you write every frame.