Skip to content

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.

You should know:

  • How async hooks and await work 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.
  • Started on demand. Nothing is opened until a script calls start() (or record() or capture(), which start the device if needed).
  • Permission once. The browser asks the player the first time. start() resolves true when the device is running, false when 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.
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.publish; null while not listening.
subscribeFrames(listener) 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(sampleRate?) A promise of a 16-bit mono WAV copy of the clip, which most speech services accept.

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.
frameAvailable() Whether a new frame arrived since the last engine frame. Optional: the texture keeps up by itself.
capture({ type?, quality?, maxSize? }) 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().

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.publish.
isSupported() Whether this browser can share a screen.

The browser’s own “Stop sharing” button ends the share for every script.

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.

VoiceMeter.jx
#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();
}
  • startup is async, so it can await Input.microphone.start(), which shows the permission prompt the first time.
  • level() is the loudness this frame, from 0 to 1; speech is usually 0.4 to 0.7. Multiplying it by SENSITIVITY (capped at 1) lets quiet speech move the cone, so it grows up to twice its size.
  • Easing towards the loudness with dt smooths out the flicker of raw audio.
  • dispose stops listening when the script goes away. The runtime would release it anyway; stopping explicitly makes the intent clear.
Mirror.jx
#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);
}
  • 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.

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.

ListenButton.jx
#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);
}
  • The button is a UI Toggle Button showing only an icon. Its UIToggleButton::change event carries the new state in event.data.checked.
  • show keeps the button’s icon (Mic or MicOff) and the label’s text in step with the microphone.
  • If the microphone does not start, setChecked(false) releases the button. The isListening() 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 async so it can await the answer.
  • level() reads 0 while not listening, so update needs no extra check: the sphere simply rests at its own size. SENSITIVITY works as in the voice-reactive object.
VoiceMessage.jx
#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.blob and clip.fileName go straight into a FormData upload with HttpRequest.post.
  • Both listeners are async so they can await. The recording variable 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, whose blob and fileName you upload the same way.
PhotoBooth.jx
#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: 1280 caps the longer side, keeping uploads small. quality trades size for JPEG quality.
  • The photo’s blob and fileName upload directly; base64() is the alternative for JSON APIs.
ShareScreen.jx
#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.publish puts the shared stream under the name room/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.publish returns is kept, to withdraw the stream when sharing stops.
  • Calling await in a non-async function. Device starts return promises. Make the hook or listener async.
  • Opening the screen picker from update. Browsers only open it in response to a click or key press. Call Input.screen.start() from a button’s listener.
  • Ignoring the false result. start() resolves false when refused or unavailable. Check it and tell the player.
  • Calling capture() every frame. Each capture encodes an image. Take photos when needed, and use texture() for live display.
  • Listing devices before permission. devices() often returns an empty list or blank names until the player has allowed access. Call start() first.
  • Keeping microphone frames. Frames from subscribeFrames are only valid during the callback. Copy the samples if you keep them.