Microphone, camera and screen
Updated
A scene can hear and see the player’s real world. Input.microphone measures how loud the player is and records clips; Input.camera streams the webcam or the phone’s camera as a live texture and takes photos; Input.screen shares a screen, a window or a browser tab. These are capture devices: they start only when a script asks, ask the browser’s permission the first time, and turn off once no script uses them. This page covers all three.
Before you start
Section titled “Before you start”You should know:
- How
asynchooks andawaitwork in a script; see Scripting. - How a UI button sends a signal to a script, since some requests must come from a click; see UI.
- For showing a live stream on a video surface, the Media Stream component; see Media and text.
How capture devices work
Section titled “How capture devices work”- Started on demand. Nothing is opened until a script calls
start()(orrecord()orcapture(), which start the device if needed). - Permission once. The browser asks the player the first time.
start()resolvestruewhen the device is running,falsewhen the player refuses, there is no such device, or the app has turned the device off. - Shared between scripts. Two scripts using the microphone share one open device. Each script’s
stop()gives up only its own use; the device turns off when nobody uses it. - Cleaned up for you. When a script is released (its Behavior removed, its entity destroyed, play stopped), its use of every device is released too, so a destroyed script never leaves the camera on.
- Stop cancels a pending start. Calling
stop()while the permission prompt is still open cancels that script’s request. A late “allow” is then not applied to it.
Microphone
Section titled “Microphone”| Member | What it does |
|---|---|
start({ device? }) |
Start listening, asking permission the first time. Resolves true once listening. device picks a microphone by id from devices(), for every script. |
stop() |
Stop listening. Recordings in progress end, and their stop() gives what they have. |
isListening() |
Whether this script is listening. |
level() |
Loudness this frame, 0 (silence) to 1. Speech is usually 0.4 to 0.7. 0 while not listening. |
record() |
Start recording, and listening if needed. Returns a recording (below). |
devices() |
A promise of every microphone, [{ id, label }]. Names, and often the list itself, appear only after permission: start() first. |
device() |
The id of the microphone listening; null while not listening. |
stream() |
The live MediaStream, to publish with Streams.; null while not listening. |
subscribe |
Calls listener with raw sound frames while this script listens. Returns a function that stops it. Copy samples before keeping them. |
isSupported() |
Whether this browser can capture and record audio. |
A recording has isRecording, seconds (how long it has recorded) and stop(), a promise of the clip. A recording ends by itself after 300 seconds.
A clip is plain data:
| Field | What it is |
|---|---|
blob |
The audio itself. |
type, format |
Its media type, and its format: webm, mp4, ogg or wav. |
fileName |
A file name with the right extension. |
duration |
Length in seconds. |
base64() |
The audio as base64 text, for JSON bodies. |
wav(sample |
A promise of a 16-bit mono WAV copy of the clip, which most speech services accept. |
Camera
Section titled “Camera”Input.camera is the device’s own camera: a laptop’s webcam, a phone’s front or back camera.
| Member | What it does |
|---|---|
start({ facing?, device?, width?, height? }) |
Start streaming, asking permission the first time. facing is 'user' (front) or 'environment' (back); device an id from devices(). Give one or the other. Naming the other facing switches the camera for every script. |
stop() |
Stop using the camera; it turns off once no script uses it. |
isStreaming() |
Whether this script is using the camera. |
texture() |
The live picture as a texture: the same object every time, for every script. It updates on its own and keeps working across stops and starts. |
image() |
The live picture’s video element, to draw on a canvas. |
frame |
Whether a new frame arrived since the last engine frame. Optional: the texture keeps up by itself. |
capture({ type?, quality?, max |
A promise of the current frame as a photo. type is 'image/jpeg' (default), 'image/png' or 'image/webp'; quality 0 to 1 (default 0.9); maxSize caps the longer side in pixels. Starts the camera if needed. |
size() |
{ width, height } of the stream; 0 × 0 while not streaming. |
facing(), device(), stream() |
The facing, the device id and the MediaStream streaming now; null while not streaming. |
devices() |
A promise of every camera, [{ id, label }]. Names often appear only after permission. |
isSupported() |
Whether this browser can stream a camera. |
A photo has blob, type, format, fileName, width, height and base64().
Screen sharing
Section titled “Screen sharing”Input.screen lets the player share a screen, a window or a browser tab.
| Member | What it does |
|---|---|
start({ audio? }) |
Open the browser’s picker. Resolves true once shared; false when cancelled, refused, unsupported or turned off by the app. Call it from a click or a key press. |
stop() |
Stop sharing. |
isStreaming() |
Whether this script is sharing. |
stream() |
The shared MediaStream, to publish with Streams.. |
isSupported() |
Whether this browser can share a screen. |
The browser’s own “Stop sharing” button ends the share for every script.
Showing a live stream in the scene
Section titled “Showing a live stream in the scene”A Video or UI Video entity with a Media Stream component plays a stream published by name in place of its file. A script publishes a capture device’s stream under that name with Streams.publish(name, stream), which returns a function that unpublishes it. The camera, microphone or screen stream stays published while the device runs; a script’s publications are withdrawn when the script is released.
Examples
Section titled “Examples”1. A voice-reactive object
Section titled “1. A voice-reactive object”#pragma lifecycle(startup, update, dispose)
const SENSITIVITY = 3; // raise it to react to quieter sounds
let listening = false;let level = 0;let speaker;
async function startup() { speaker = findEntity('Speaker Cone'); listening = await Input.microphone.start(); if (!listening) log('No microphone, or permission refused');}
function update(dt) { if (!listening) return; const loudness = Math.min(1, Input.microphone.level() * SENSITIVITY); // Ease towards the new level so the object does not jitter. level += (loudness - level) * Math.min(1, dt * 12); speaker.scale.setScalar(1 + level);}
function dispose() { Input.microphone.stop();}A speaker cone grows with the loudness of your voice: the script starts Input.microphone at startup and eases the cone towards level() every frame.
Allow the microphone when the browser asks, then speak or clap. Needs a microphone and your permission. Drag to orbit the camera, scroll to zoom.
startupisasync, so it canawait Input.microphone.start(), which shows the permission prompt the first time.level()is the loudness this frame, from0to1; speech is usually 0.4 to 0.7. Multiplying it bySENSITIVITY(capped at1) lets quiet speech move the cone, so it grows up to twice its size.- Easing towards the loudness with
dtsmooths out the flicker of raw audio. disposestops listening when the script goes away. The runtime would release it anyway; stopping explicitly makes the intent clear.
2. A mirror from the front camera
Section titled “2. A mirror from the front camera”#pragma lifecycle(startup)
async function startup() { if (!Input.camera.isSupported()) return log('No camera here'); if (!(await Input.camera.start({ facing: 'user' }))) return log('No camera, or permission refused');
const { width, height } = Input.camera.size(); const aspect = height > 0 ? width / height : 16 / 9;
const screen = new THREE.Mesh( new THREE.PlaneGeometry(aspect, 1), new THREE.MeshBasicMaterial({ map: Input.camera.texture() }), ); screen.scale.x = -1; // flip, like a mirror findEntity('Mirror Frame').add(screen);}Input.camera starts the front camera and its live texture is shown, flipped like a mirror, on a plane added to a frame.
Allow the camera when the browser asks, then wave at the mirror. Needs a camera and your permission. Drag to orbit the camera, scroll to zoom.
start({ facing: 'user' })asks for the front camera.size()gives the stream’s resolution, used to make the plane the right shape.texture()is a live texture that updates by itself, so the mesh shows the camera without any per-frame code.- Flipping the plane’s X scale makes it behave like a mirror, which is what people expect from a front camera.
3. A voice meter started from a button
Section titled “3. A voice meter started from a button”The same idea as the voice-reactive object, but the microphone starts only when the player asks. A panel holds a microphone toggle button and a label: pressing the button starts listening, pressing it again stops.
#pragma lifecycle(startup, update)
const SENSITIVITY = 3; // raise it to react to quieter sounds
let speaker;let button;let label;let level = 0;
// The button's icon and the label follow the microphone.function show(listening, text) { button.setProps({ icon: listening ? 'Mic' : 'MicOff' }); label.setProps({ text });}
function startup() { speaker = findEntity('Speaker'); button = findEntity('Mic Button').getComponent(UIToggleButtonComponent); label = findEntity('Mic Label').getComponent(UILabelComponent); if (!Input.microphone.isSupported()) return show(false, 'This browser cannot capture audio');
on('ui/listen', async (event) => { if (event.eventType !== EventType.UIToggleButton.Change) return; if (!event.data.checked) { if (!Input.microphone.isListening()) return; // unchecked below, after a refusal Input.microphone.stop(); return show(false, 'Microphone off'); } if (await Input.microphone.start()) return show(true, 'Listening: speak or clap'); button.setChecked(false); show(false, 'No microphone, or permission refused'); });}
function update(dt) { // level() is 0 while not listening, so the sphere rests at its own size. const loudness = Math.min(1, Input.microphone.level() * SENSITIVITY); level += (loudness - level) * Math.min(1, dt * 12); speaker.scale.setScalar(1 + level);}A sphere grows with the loudness of your voice: a microphone toggle button starts and stops Input.microphone, a label says what it is doing, and the script eases the sphere towards level() every frame.
Press the microphone button and allow the microphone, then speak or clap. Press it again to stop. Needs a microphone and your permission. Drag to orbit the camera, scroll to zoom.
- The button is a UI Toggle Button showing only an icon. Its
UIToggleButton::changeevent carries the new state inevent.data.checked. showkeeps the button’s icon (MicorMicOff) and the label’s text in step with the microphone.- If the microphone does not start,
setChecked(false)releases the button. TheisListening()check makes the listener ignore that change. isSupported()is checked first, so a browser that cannot capture audio says so in the label.- The permission prompt follows a button press, which players expect, and the listener is
asyncso it canawaitthe answer. level()reads0while not listening, soupdateneeds no extra check: the sphere simply rests at its own size.SENSITIVITYworks as in the voice-reactive object.
Snippets
Section titled “Snippets”1. Record a message and upload it
Section titled “1. Record a message and upload it”#pragma lifecycle(startup)
let recording = null;
function startup() { // Two UI buttons send their presses on 'ui/record' and 'ui/send'. on('ui/record', async (event) => { if (event.eventType !== EventType.UIButton.Press || recording) return; if (!(await Input.microphone.start())) return log('No microphone'); recording = Input.microphone.record(); log('Recording…'); });
on('ui/send', async (event) => { if (event.eventType !== EventType.UIButton.Press || !recording) return; const clip = await recording.stop(); recording = null; Input.microphone.stop();
log(`Recorded ${clip.duration.toFixed(1)} s of ${clip.format}`); const form = new FormData(); form.append('file', clip.blob, clip.fileName); await HttpRequest.post('https://api.example.com/messages', { body: form }); log('Sent'); });}- The record button starts the microphone and then
record(), which returns a recording object at once. - The send button awaits
recording.stop(), which resolves to the clip.clip.blobandclip.fileNamego straight into aFormDataupload withHttpRequest.post. - Both listeners are
asyncso they canawait. Therecordingvariable stops a second press from starting a second recording. - For a speech service that wants WAV, convert first:
const wav = await clip.wav(16000)gives another clip, a 16 kHz mono WAV, whoseblobandfileNameyou upload the same way.
2. A photo booth
Section titled “2. A photo booth”#pragma lifecycle(startup)
let shots = 0;
function startup() { // A UI button sends its presses on 'ui/snap'. on('ui/snap', async (event) => { if (event.eventType !== EventType.UIButton.Press) return;
const photo = await Input.camera.capture({ type: 'image/jpeg', quality: 0.85, maxSize: 1280 }); shots += 1; log(`Photo ${shots}: ${photo.width} × ${photo.height}, ${photo.blob.size} bytes`);
const form = new FormData(); form.append('photo', photo.blob, photo.fileName); await HttpRequest.post('https://api.example.com/booth', { body: form }); emit('booth/saved', { count: shots }); });}capture()starts the camera if needed (asking permission the first time) and resolves to a photo of the current frame.maxSize: 1280caps the longer side, keeping uploads small.qualitytrades size for JPEG quality.- The photo’s
blobandfileNameupload directly;base64()is the alternative for JSON APIs.
3. Share a screen onto a virtual display
Section titled “3. Share a screen onto a virtual display”#pragma lifecycle(startup)
const STREAM = 'room/screen';let unpublish = null;
function startup() { // A UI button sends its presses on 'ui/share'. The Display entity is a Video // with a Media Stream component whose stream is 'room/screen'. on('ui/share', async (event) => { if (event.eventType !== EventType.UIButton.Press) return;
if (Input.screen.isStreaming()) { Input.screen.stop(); if (unpublish) unpublish(); unpublish = null; return; }
if (!Input.screen.isSupported()) return log('Screen sharing is not supported here'); if (!(await Input.screen.start())) return log('Sharing cancelled'); unpublish = Streams.publish(STREAM, Input.screen.stream()); });}- The same button toggles sharing:
isStreaming()says whether this script is sharing now. start()opens the browser’s picker, so it must come from a click: here, the button press.Streams.publishputs the shared stream under the nameroom/screen. The Video entity’s Media Stream component plays whatever is published under that name, so the virtual display shows the shared screen.- The function
Streams.publishreturns is kept, to withdraw the stream when sharing stops.
Common mistakes
Section titled “Common mistakes”- Calling
awaitin a non-async function. Device starts return promises. Make the hook or listenerasync. - Opening the screen picker from
update. Browsers only open it in response to a click or key press. CallInput.screen.start()from a button’s listener. - Ignoring the
falseresult.start()resolvesfalsewhen refused or unavailable. Check it and tell the player. - Calling
capture()every frame. Each capture encodes an image. Take photos when needed, and usetexture()for live display. - Listing devices before permission.
devices()often returns an empty list or blank names until the player has allowed access. Callstart()first. - Keeping microphone frames. Frames from
subscribeFramesare only valid during the callback. Copy the samples if you keep them.