konowebcodecs/examples/browser/webcam.html
2020-11-03 15:39:01 +08:00

73 lines
2.3 KiB
HTML

<html>
<head>
<script src="/dist/ffmpeg.dev.js"></script>
<style>
html, body {
margin: 0;
width: 100%;
height: 100%
}
body {
display: flex;
flex-direction: column;
align-items: center;
}
</style>
</head>
<body>
<h3>Record video from webcam and transcode to mp4 (x264) and play!</h3>
<div>
<video id="webcam" width="320px" height="180px"></video>
<video id="output-video" width="320px" height="180px" controls></video>
</div>
<button id="record" disabled>Start Recording</button>
<p id="message"></p>
<script>
const { createFFmpeg, fetchFile } = FFmpeg;
const ffmpeg = createFFmpeg({ log: true });
const webcam = document.getElementById('webcam');
const recordBtn = document.getElementById('record');
const startRecording = () => {
const rec = new MediaRecorder(webcam.srcObject);
const chunks = [];
recordBtn.textContent = 'Stop Recording';
recordBtn.onclick = () => {
rec.stop();
recordBtn.textContent = 'Start Recording';
recordBtn.onclick = startRecording;
}
rec.ondataavailable = e => chunks.push(e.data);
rec.onstop = async () => {
transcode(new Uint8Array(await (new Blob(chunks)).arrayBuffer()));
};
rec.start();
};
(async () => {
webcam.srcObject = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
await webcam.play();
recordBtn.disabled = false;
recordBtn.onclick = startRecording;
})();
const transcode = async (webcamData) => {
const message = document.getElementById('message');
const name = 'record.webm';
message.innerHTML = 'Loading ffmpeg-core.js';
await ffmpeg.load();
message.innerHTML = 'Start transcoding';
ffmpeg.FS('writeFile', name, await fetchFile(webcamData));
await ffmpeg.run('-i', name, 'output.mp4');
message.innerHTML = 'Complete transcoding';
const data = ffmpeg.FS('readFile', 'output.mp4');
const video = document.getElementById('output-video');
video.src = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
}
</script>
</body>
</html>