Handle Local Media for JavaScript
To send media in a video conference, you must produce local audio and video. Audio or video produced by the current user is called local media. This article describes how to capture local media and send it to remote participants.
You don't need to implement local media because LiveSwitch provides local media that works with major browsers. To use local media, create an instance of fm.liveswitch.LocalMedia
. Provide two parameters audio
and video
, which indicate whether to capture audio and whether to capture video. If you want to capture both, pass true
for both parameters.
For example:
var audio = true;
var video = true;
var localMedia = new fm.liveswitch.LocalMedia(audio, video);
// For more control, the video parameter can be an instance of fm.liveswitch.VideoConfig. Doing this lets you specify a width, height, and frame rate.
var audio = true;
var video = new fm.liveswitch.VideoConfig(width, height, frameRate);
var localMedia = new fm.liveswitch.LocalMedia(audio, video);
// For more advanced or experimental use cases, the audio and video parameters can be HTML5-compliant MediaTrackConstraints definitions:
var audio = {
sampleSize: 16,
channelCount: 2,
echoCancellation: false
};
var video = {
width: 320,
height: 240,
frameRate: 30
};
var localMedia = new fm.liveswitch.LocalMedia(audio, video);
Note
LiveSwitch passes constraints through to the browser's getUserMedia
API. Browser support for some constraints might vary depending on the browser's version.
For ultimate flexibility, the audio and video parameters also accept an HTML5 media stream. The following code example shows how to stream media to an HTML canvas:
var canvas = document.getElementById('localCanvasSource');
var canvasFrameRate = 3;
if (!canvas) {
// Create the canvas if it doesn't exist yet.
canvas = document.createElement('canvas');
canvas.id = 'localCanvasSource';
canvas.style.position = 'absolute';
document.body.appendChild(canvas);
// Load a static image.
var image = new Image();
image.onload = function() {
// Resize the canvas to match the image size.
canvas.width = image.width;
canvas.height = image.height;
canvas.style.left = '-' + image.width + 'px';
canvas.style.top = '-' + image.height + 'px';
// Draw the initial image.
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
// Refresh the image on a regular interval.
window.setInterval(function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}, 1000.0 / canvasFrameRate);
};
image.src = 'https://v1.liveswitch.fm/images/static.jpg';
}
var audio = false;
var video = canvas.captureStream(canvasFrameRate);
var localMedia = new fm.liveswitch.LocalMedia(audio, video);