Skip to main content

Webcaster guides

These guides show how to do the common tasks with nanoStream Webcaster v6. Each section has a complete, working snippet. If you haven't sent your first stream yet, start with nanoStream Webcaster: getting started.

All snippets assume the SDK is loaded with a script tag and run inside an async function or a module, so await works:

const { Webcaster, DeviceUtils, HelperUtils } = window.WebcasterApiV6;

serverUrl and ingestUrl default to https://bintu-webrtc.nanocosmos.de/p/webrtc and rtmp://bintu-stream.nanocosmos.de:1935/live, so most snippets only set streamName. Replace <YOUR_STREAM_NAME> with your stream name.

Input sources​

The Webcaster takes its video and audio from a MediaStream. You have two options:

  • Let the Webcaster create it from your settings in inputCfg.mediaStreamCfg.
  • Create it yourself with the browser's MediaDevices API (camera, microphone, screen) or from a canvas, and pass it in inputCfg.mediaStream.

If you pass mediaStream, mediaStreamCfg is ignored.

Let the Webcaster open camera and microphone​

const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: {
mediaStreamCfg: {
maxFramerate: 30,
resolution: [1280, 720],
audioConstraints: {
autoGainControl: true,
channelCount: 2,
echoCancellation: true,
noiseSuppression: true
}
}
}
});

await client.setup(); // asks for camera and microphone access
await client.startBroadcast();

Pass your own camera and microphone stream​

Use getUserMedia when you want full control over the constraints:

const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: { mediaStream: stream }
});

await client.setup();
await client.startBroadcast();

Share your screen​

Screen sharing works in desktop browsers only. Capture the screen with getDisplayMedia and combine it with the microphone:

const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true });

const audioTrack = micStream.getAudioTracks()[0];
const videoTrack = screenStream.getVideoTracks()[0];

// One MediaStream: screen video + microphone audio
const stream = new MediaStream([videoTrack, audioTrack]);

const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: { mediaStream: stream }
});

await client.setup();
await client.startBroadcast();

// Stop the webcast when the user clicks the browser's "Stop sharing" button
videoTrack.addEventListener('ended', () => client.stopBroadcast());

The hosted screen share sample shows the same flow: https://nanocosmos.github.io/webcaster/samples/screenshare/index.html?streamName=<YOUR_STREAM_NAME>.

Stream a canvas​

You can draw anything into an HTML canvas (overlays, mixed sources, graphics) and stream it with captureStream:

  1. Get your video, image and audio sources.
  2. Draw them into a canvas in a render loop.
  3. Optionally add an audio track to the canvas stream.
  4. Pass the stream to the Webcaster.
<canvas id="my-canvas" width="1280" height="720"></canvas>
const framerate = 30;
const canvas = document.getElementById('my-canvas');
const context = canvas.getContext('2d');

// MediaStream from the canvas
const canvasStream = canvas.captureStream(framerate);

// Optional: add the microphone
const micStream = await navigator.mediaDevices.getUserMedia({ audio: true });
canvasStream.addTrack(micStream.getAudioTracks()[0]);

// Render loop: redraw the frame `framerate` times per second
function renderLoop() {
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
context.fillStyle = '#fff';
context.font = '50px sans-serif';
context.fillText(new Date().toLocaleTimeString(), 50, 90);
setTimeout(renderLoop, 1000 / framerate);
}
renderLoop();

const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: { mediaStream: canvasStream }
});

await client.setup();
await client.startBroadcast();

With canvas streams you are responsible for the rendering:

  • Keep the frame rate steady. A dropping frame rate increases end-to-end latency.
  • Watch for tab throttling. When the tab loses focus, most browsers slow down timers such as setTimeout. Listen for the visibilitychange event and warn your users.
  • Expect adaptation. The browser's encoder can lower the resolution, for example when it detects CPU overuse.

Select camera and microphone​

The DeviceUtils helpers list the devices the browser can use:

FunctionWhat it does
DeviceUtils.getAvailableMediaDevices(audioVideoOnly?)Returns a Promise<MediaDeviceInfo[]> of all devices. Pass 'audio' or 'video' to only probe that kind, so a missing camera doesn't block listing microphones.
DeviceUtils.filterDevices(devices, kinds?, groupId?, deviceId?)Filters the list. kinds defaults to ['audioinput', 'videoinput'].

The list only includes devices the user has granted permission for on this page. Browsers may store a denial per site; see getUserMedia and the Permissions API.

Show a device picker​

<label for="video-select">Camera</label>
<select id="video-select"></select>
<label for="audio-select">Microphone</label>
<select id="audio-select"></select>
<button id="go">Go live</button>
<video id="preview" muted autoplay playsinline></video>
function fillSelect(select, devices) {
for (const device of devices) {
const option = document.createElement('option');
option.value = device.deviceId;
option.textContent = device.label || 'Unknown device';
select.appendChild(option);
}
}

const devices = await DeviceUtils.getAvailableMediaDevices();
fillSelect(document.getElementById('video-select'), DeviceUtils.filterDevices(devices, ['videoinput']));
fillSelect(document.getElementById('audio-select'), DeviceUtils.filterDevices(devices, ['audioinput']));

document.getElementById('go').addEventListener('click', async () => {
const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
previewVideoElId: 'preview',
inputCfg: {
mediaStreamCfg: {
videoDeviceId: document.getElementById('video-select').value,
audioDeviceId: document.getElementById('audio-select').value,
maxFramerate: 30,
resolution: [1280, 720]
}
}
});
await client.setup();
client.startPreview();
await client.startBroadcast();
});

videoDeviceId and audioDeviceId are optional. Leave them out (or empty) to use the browser's default device.

Switch devices​

The configuration you pass to the constructor can't be changed later. To switch camera or microphone, stop and dispose the current instance, then create a new one with the new device IDs:

let client = createClient(firstCameraId);
await client.setup();
await client.startBroadcast();

function createClient(videoDeviceId) {
return new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
previewVideoElId: 'preview',
inputCfg: { mediaStreamCfg: { videoDeviceId } }
});
}

async function switchCamera(newCameraId) {
await client.dispose(true); // stops the broadcast; true also stops the camera and mic tracks
client = createClient(newCameraId);
await client.setup();
client.startPreview();
await client.startBroadcast();
}

Viewers see a short interruption while the new broadcast starts.

Audio-only and video-only​

Set inputCfg.mediaStreamCfg.audioVideoOnly to 'audio' or 'video'. Since 6.2.4 the SDK only asks for permission for the kind you use, so a missing or denied camera no longer blocks an audio-only webcast.

// Audio only
const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: { mediaStreamCfg: { audioVideoOnly: 'audio' } }
});

await client.setup();
await client.startBroadcast();

Use audioVideoOnly: 'video' for a stream without audio.

Quality settings​

You control quality in two places:

WhereKeyWhat it sets
Capture (inputCfg.mediaStreamCfg)resolutionRequested [width, height]. An ideal value: the browser picks the closest it can deliver.
maxFramerateUpper limit for the capture frame rate
audioConstraintsautoGainControl, echoCancellation, noiseSuppression, channelCount
Encoding (inputCfg.broadcastCfg)maxVideoBitrateBpsMaximum video bitrate, in bits per second
maxAudioBitrateBpsMaximum audio bitrate sent from the browser, in bits per second
maxEncodingFramerateMaximum encoded frame rate. Can't be higher than maxFramerate.
transcodeAudioBitrateBpsAudio bitrate after server-side conversion, in bits per second
const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: {
mediaStreamCfg: {
resolution: [1280, 720],
maxFramerate: 30
},
broadcastCfg: {
maxVideoBitrateBps: HelperUtils.kbps(1500),
maxAudioBitrateBps: HelperUtils.kbps(128),
maxEncodingFramerate: 30,
transcodeAudioBitrateBps: HelperUtils.kbps(64)
}
}
});

await client.setup();
await client.startBroadcast();

Bitrates are upper limits. The browser only uses the full bitrate for complex pictures with a lot of motion; with little movement or a dark picture the bitrate is lower. Video passes through the server unchanged, so the RTMP stream has about the bitrate the browser encoded. Audio is converted on the server, which is why you can set transcodeAudioBitrateBps. HelperUtils.kbps(n) and HelperUtils.mbps(n) convert to bits per second.

A browser has less headroom than a dedicated encoder. Start conservative and increase only if source and network can handle it:

SourceResolutionVideo bitrate
Webcam640×480400–800 kbps
Webcam1280×7201000–1500 kbps
Screen shareScreen size1000–2000 kbps (depends on motion)
High-quality camera1920×10802000–3000 kbps

Speech and music audio​

Browsers apply three audio filters by default:

FilterWhat it does
autoGainControlKeeps the overall volume steady
echoCancellationPrevents echo
noiseSuppressionRemoves background noise

Turn all three on for speech (talks, hosts, commentary) and off for music, where they distort the sound:

// Music: disable the voice filters
const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
inputCfg: {
mediaStreamCfg: {
audioConstraints: {
autoGainControl: false,
echoCancellation: false,
noiseSuppression: false
}
}
}
});

await client.setup();
await client.startBroadcast();

For speech, set all three to true. If you pass your own MediaStream, set these constraints in your own getUserMedia call instead.

Mute audio or video​

setMuted() mutes audio, video or both, during a broadcast or before setup(). isMuted() returns the current state.

client.setMuted({ audio: true }); // mute the microphone
client.setMuted({ audio: false, video: true }); // unmute audio, black out video
console.log(client.isMuted()); // { audio: false, video: true }

To start muted, set inputCfg.muted, for example muted: { audio: true }.

Send live metadata​

sendMetadata(handlerName, data) adds live metadata to the running broadcast, for example to sync events with the video. handlerName is 'onMetaData' or 'onCuePoint'; data is an object with a maximum depth of 6.

await client.sendMetadata('onMetaData', { question: 3, state: 'open' });

Players receive the metadata with the stream; see Player features and Stream tags & metadata.

Multiple webcasts​

You can broadcast several streams from one browser tab, for example camera plus screen share, several cameras, or several audio sources. Create one Webcaster instance per stream, each with its own stream name.

// 1. Camera instance: the SDK creates the MediaStream with default settings
const camClient = new Webcaster({
streamName: '<YOUR_STREAM_NAME_1>'
});

// 2. Screen share instance: pass your own MediaStream
const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true });
const screenClient = new Webcaster({
streamName: '<YOUR_STREAM_NAME_2>',
inputCfg: { mediaStream: screenStream }
});

// 3. Set up both instances (in parallel)
await Promise.all([camClient.setup(), screenClient.setup()]);

// 4. Optional: one preview per instance
camClient.startPreview('camera-preview');
screenClient.startPreview('screenshare-preview');

// 5. Start both broadcasts (in parallel)
await Promise.all([camClient.startBroadcast(), screenClient.startBroadcast()]);
<video id="camera-preview" muted autoplay playsinline></video>
<video id="screenshare-preview" muted autoplay playsinline></video>

Every extra webcast adds encoding load and upload bandwidth. Check CPU and upstream before you add more.

Automatic reconnection​

The Webcaster can reconnect on its own after an unintended disconnect, for example when a phone switches from Wi-Fi to cellular, when moving between Wi-Fi networks, or during a short outage.

Turn it on with reconnect: true (defaults below) or pass your own values:

KeyDefaultDescription
minDelaySec2Minimum wait before a reconnect attempt, in seconds. Minimum 1.
maxDelaySec15Maximum wait before a reconnect attempt, in seconds. Minimum 1.
maxRetries10Maximum number of attempts in a row before giving up. Minimum 1.
const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
reconnect: {
minDelaySec: 2,
maxDelaySec: 15,
maxRetries: 10
}
});

client.onReconnectionStateChange = (state) => {
console.log('Reconnection state:', state); // 'idle' | 'reconnecting' | 'failed'
};

await client.setup();
await client.startBroadcast();
tip

Let the total reconnect time exceed one minute. That gives DNS changes (record TTLs) time to take effect.

ReconnectionStateMeaning
idleInitial state; nothing is happening.
reconnectingThe connection failed and a reconnect is underway.
failedThe retry limit is reached and the SDK stopped trying. Call recover() before you start a new broadcast.
client.onReconnectionStateChange = async (state) => {
if (state === 'failed') {
await client.recover();
await client.startBroadcast();
}
};

Stats and metrics​

The Webcaster reports quality of service in two ways: metrics in your page, and metrics sent to nanocosmos for nanoStream Analytics.

Read metrics in the browser​

onMetrics is called at an interval once the broadcast runs. Error metrics are reported straight away, independent of the interval.

client.onMetrics = (metrics) => {
console.log(metrics);
if (metrics.errorMessage) {
console.warn(metrics.errorCode, metrics.errorMessage);
}
};

await client.setup();
await client.startBroadcast(); // also starts the metrics interval

Show an ingest quality indicator​

Three values tell you about the upstream from the broadcaster's browser to the nanocosmos server:

  • RTT (round-trip time): time in milliseconds for data to go to the server and back.
  • Packet loss: percentage of packets lost in the past 10 seconds.
  • Send delay (Chromium-based browsers only): delay before video frames are sent.

Use them for a traffic light in your broadcaster UI:

IndicatorGoodWatchAct
RTT150 ms or less150–250 ms: viewer experience may degrade slightlyAbove 250 ms: check the network
Packet lossBelow 5%5–10%: may degrade, especially at 2 Mbps and aboveAbove 10%: the stream can stutter
client.onMetrics = (metrics) => {
const rtt = metrics.rtcstats?.connection?.rtt?.value;
const packetLoss = metrics.rtcstats?.connection?.packetLoss?.value;

// Values can be missing early in a session
if (rtt == null || packetLoss == null) return;

let quality = 'good';
if (packetLoss > 10 || rtt > 250) {
quality = 'bad';
} else if (packetLoss >= 5 || rtt > 150) {
quality = 'medium';
}

console.log({ rtt, packetLoss, quality });
};

Send metrics to nanoStream Analytics​

Sending client metrics to nanocosmos helps you analyse ingest quality and track browser-side problems. They appear in the Webcaster view of the Analytics dashboard: publishes per OS and browser, video and audio bitrates, ingest time, error and status codes, reasons for stopping and Webcaster versions. Add your metrics credentials to the config:

const client = new Webcaster({
streamName: '<YOUR_STREAM_NAME>',
metrics: {
accountId: '<YOUR_METRICS_ACCOUNT_ID>',
accountKey: '<YOUR_METRICS_ACCOUNT_KEY>'
}
});

Troubleshooting​

ProblemWhat to check
No camera or microphone, or a permission errorCheck the browser's permission icon in the address bar. Make sure the page is served over HTTPS. Close other apps or tabs using the camera. Try another device.
setup() fails with code 2003 (MStreamNotCreated)The browser couldn't create the MediaStream: no device, device busy, or permission denied.
startBroadcast() fails with 11001 / 10003The WebRTC server couldn't be reached or returned an error. Check firewall or VPN rules for WebRTC traffic, and test on another network.
5002 (BroadcastPCAlreadyExists)startBroadcast() was called twice. Wait for the first promise.
Video lags or stutters for all viewersUsually the broadcaster side: bitrate too high for the upload, CPU overload, or an unstable source frame rate. Test at 640×480 and 600 kbps, then step up.
Stream drops on network changesTurn on automatic reconnection.

All error codes are listed in the API reference. For network checks, see Network diagnostics.

When you contact support, include:

  • a description of the problem, what you expected, and when it happened
  • your Webcaster configuration and the stream name or stream ID
  • steps to reproduce it
  • the browser console log (Ctrl+Shift+J or F12 on Windows/Linux, Cmd+Opt+J on Mac)
  • in Chrome, a dump from chrome://webrtc-internals (click dump and download it)

See Get support.

FAQ​

Which browsers are supported?​

Current versions of Chrome, Firefox, Edge (Chromium-based), Safari and Opera, on desktop and mobile, for camera and microphone. Screen sharing works on desktop browsers only. The browser must support H.264 video and Opus audio encoding.

Which cameras work?​

Any camera the browser can open with getUserMedia. Camera support depends on the browser, not on the Webcaster.

Does the Webcaster work in a mobile app WebView?​

The SDK needs WebRTC and camera access in the WebView. Android WebView works. On iOS, check whether your app's WebView grants camera access before you rely on it; Safari itself works.

Can I switch the camera during a broadcast?​

Not on a running instance: the configuration is fixed. Stop the broadcast, dispose the instance, and create a new one with the new device ID. See Switch devices.

Do I need an API key in the browser?​

No. The Webcaster only needs the stream name. Create streams on your backend with the nanoStream REST API and never put your API key in a web page.

How do I know the broadcast is live?​

startBroadcast() resolves when the connection is established. For the ongoing state, use onStateChange with getUpstreamStatus().connectionState, or onConnectionStateChange.

Can I add ABR renditions to a Webcaster stream?​

Yes. The Webcaster sends one quality, and it can ingest into live transcoding, which creates the other qualities. See Adaptive Bitrate Streaming & live transcoding.

Where are the version 5 questions?​

Version 5 is legacy. See Legacy & retired docs.

Next steps​