Platform
Recording Video
This guide serves as an example of how you may record video of your Camera Kit session's output canvas.
index.html
<html>
<head>
<title>Recording Video</title>
</head>
<body>
<section>
<canvas id="canvas"></canvas>
</section>
<section>
<button id="start">Start Recording</button>
<button id="stop" disabled>Stop Recording</button>
</section>
<section id="video-container" style="display: none">
<video loop controls autoplay id="video"></video>
<div>
<button id="download">Download Video</button>
</div>
</section>
<script type="module" src="script.ts"></script>
</body>
</html>
script.ts
import { bootstrapCameraKit, createMediaStreamSource } from '@snap/camera-kit';
const liveRenderTarget = document.getElementById('canvas') as HTMLCanvasElement;
const videoContainer = document.getElementById(
'video-container'
) as HTMLElement;
const videoTarget = document.getElementById('video') as HTMLVideoElement;
const startRecordingButton = document.getElementById(
'start'
) as HTMLButtonElement;
const stopRecordingButton = document.getElementById(
'stop'
) as HTMLButtonElement;
const downloadButton = document.getElementById('download') as HTMLButtonElement;
let mediaRecorder: MediaRecorder;
let downloadUrl: string;
async function init() {
const cameraKit = await bootstrapCameraKit({
apiToken: '<API_TOKEN>',
});
const session = await cameraKit.createSession({ liveRenderTarget });
const mediaStream = await navigator.mediaDevices.getUserMedia({
video: true,
});
const source = createMediaStreamSource(mediaStream);
await session.setSource(source);
await session.play();
const { lenses } = await cameraKit.lensRepository.loadLensGroups([
'<LENS_GROUP_ID>',
]);
session.applyLens(lenses[0]);
bindRecorder();
}
function bindRecorder() {
startRecordingButton.addEventListener('click', () => {
startRecordingButton.disabled = true;
stopRecordingButton.disabled = false;
downloadButton.disabled = true;
videoContainer.style.display = 'none';
const mediaStream = liveRenderTarget.captureStream(30);
mediaRecorder = new MediaRecorder(mediaStream);
mediaRecorder.addEventListener('dataavailable', (event) => {
if (!event.data.size) {
console.warn('No recorded data available');
return;
}
const blob = new Blob([event.data]);
downloadUrl = window.URL.createObjectURL(blob);
downloadButton.disabled = false;
videoTarget.src = downloadUrl;
videoContainer.style.display = 'block';
});
mediaRecorder.start();
});
stopRecordingButton.addEventListener('click', () => {
startRecordingButton.disabled = false;
stopRecordingButton.disabled = true;
mediaRecorder?.stop();
});
downloadButton.addEventListener('click', () => {
const link = document.createElement('a');
link.setAttribute('style', 'display: none');
link.href = downloadUrl;
link.download = 'camera-kit-web-recording.webm';
link.click();
link.remove();
});
}
init();
Was this page helpful?