Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created August 25, 2018 19:26
Show Gist options
  • Save prof3ssorSt3v3/48621be79794a8a3adeed7971786d4d8 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/48621be79794a8a3adeed7971786d4d8 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MediaCapture and Streams API</title>
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="main.css">
</head>
<body>
<header>
<h1>MediaCapture, MediaRecorder and Streams API</h1>
</header>
<main>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit molestiae itaque facere totam saepe tempore esse temporibus, quae reprehenderit aliquid iusto ea laborum, iure eligendi odio exercitationem sapiente illum quos.</p>
<p><button id="btnStart">START RECORDING</button><br/>
<button id="btnStop">STOP RECORDING</button></p>
<video controls></video>
<video id="vid2" controls></video>
<!-- could save to canvas and do image manipulation and saving too -->
</main>
<script>
let constraintObj = {
audio: false,
video: {
facingMode: "user",
width: { min: 640, ideal: 1280, max: 1920 },
height: { min: 480, ideal: 720, max: 1080 }
}
};
// width: 1280, height: 720 -- preference only
// facingMode: {exact: "user"}
// facingMode: "environment"
//handle older browsers that might implement getUserMedia in some way
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
navigator.mediaDevices.getUserMedia = function(constraintObj) {
let getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraintObj, resolve, reject);
});
}
}else{
navigator.mediaDevices.enumerateDevices()
.then(devices => {
devices.forEach(device=>{
console.log(device.kind.toUpperCase(), device.label);
//, device.deviceId
})
})
.catch(err=>{
console.log(err.name, err.message);
})
}
navigator.mediaDevices.getUserMedia(constraintObj)
.then(function(mediaStreamObj) {
//connect the media stream to the first video element
let video = document.querySelector('video');
if ("srcObject" in video) {
video.srcObject = mediaStreamObj;
} else {
//old version
video.src = window.URL.createObjectURL(mediaStreamObj);
}
video.onloadedmetadata = function(ev) {
//show in the video element what is being captured by the webcam
video.play();
};
//add listeners for saving video/audio
let start = document.getElementById('btnStart');
let stop = document.getElementById('btnStop');
let vidSave = document.getElementById('vid2');
let mediaRecorder = new MediaRecorder(mediaStreamObj);
let chunks = [];
start.addEventListener('click', (ev)=>{
mediaRecorder.start();
console.log(mediaRecorder.state);
})
stop.addEventListener('click', (ev)=>{
mediaRecorder.stop();
console.log(mediaRecorder.state);
});
mediaRecorder.ondataavailable = function(ev) {
chunks.push(ev.data);
}
mediaRecorder.onstop = (ev)=>{
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
chunks = [];
let videoURL = window.URL.createObjectURL(blob);
vidSave.src = videoURL;
}
})
.catch(function(err) {
console.log(err.name, err.message);
});
/*********************************
getUserMedia returns a Promise
resolve - returns a MediaStream Object
reject returns one of the following errors
AbortError - generic unknown cause
NotAllowedError (SecurityError) - user rejected permissions
NotFoundError - missing media track
NotReadableError - user permissions given but hardware/OS error
OverconstrainedError - constraint video settings preventing
TypeError - audio: false, video: false
*********************************/
</script>
</body>
</html>
@BenDurmishllari
Copy link

As you build this code is any option to add echo cancelation?

@BenDurmishllari
Copy link

BenDurmishllari commented Feb 14, 2020

I founded anyway thank you for you time :)
if anyone have the same problem just add this on html: " muted="muted"

@prof3ssorSt3v3
Copy link
Author

You have to use the insert code button to add HTML

@BenDurmishllari
Copy link

Hi,

Instead of streaming the record video through the "vid2" video element on the same page, how we can stream it in an another html page?

@prof3ssorSt3v3
Copy link
Author

That is a whole other level of complexity. You need to have a server-side script that can create the connections between the browsers and then you use WebRTC to stream the data from one to the other.

@oelgoubi
Copy link

oelgoubi commented Mar 2, 2020

hey Steve !
is there any alternative for this API that do the same work but supported by safari and IE browser ?

@prof3ssorSt3v3
Copy link
Author

IE no. Now that MS Edge is running Chromium it will be supporting everything.

Safari is slowly adding support. They always lag behind. Older Safari no.

@Dharmendrathapa3
Copy link

When start button is click this error: "GET blob:null/f1b7bf76-7923-46e0-a93c-8304fb1e1e75 net::ERR_REQUEST_RANGE_NOT_SATISFIABLE" was show and unable to record live-stream. What is the issue in my code. can you help me

@sucksucks
Copy link

Sir , how can I implement this code in canvas html5

Copy link

ghost commented May 29, 2020

Hi.
Thanks for your great code.
I want to know how to save video to server.
I am using php and javascript and framework is codeigniter.
I hope you teach this way.
Thanks.

@Bakocom
Copy link

Bakocom commented Jun 9, 2020

Cool code! Instead of the webcam coming on instantly, how can you make it start when you just hit the start button?

@prof3ssorSt3v3
Copy link
Author

Cool code! Instead of the webcam coming on instantly, how can you make it start when you just hit the start button?

Just put all that code inside a function called with addEventListener( ) for the click on the button.

@Bakocom
Copy link

Bakocom commented Jun 11, 2020

That worked but now I have another problem lol. I wrote a small Ajax code to send the blob to the server but every time I hit rerecord and make a new video the old ones are still being saved and when I finely do send it, it will send every video that has a blob URL. How do you send the last video blob URL file? formdata.append("video",blob); Maybe that is not right?

@prof3ssorSt3v3
Copy link
Author

Have a look at revokeObjectURL to get rid of old ones https://developer.mozilla.org/en-US/docs/Web/API/URL/revokeObjectURL

@Bakocom
Copy link

Bakocom commented Jun 11, 2020

Cool! I will check it out thanks!

@docouss
Copy link

docouss commented Jul 5, 2020

hello sir
what if i want to save the recorders in a server for access to them and maybe download them ? thanks ..

@prof3ssorSt3v3
Copy link
Author

hello sir
what if i want to save the recorders in a server for access to them and maybe download them ? thanks ..

You can use fetch( ) to upload the recordings to your server. You will have to write the server-side code to save the uploaded files though.

@QIEPS
Copy link

QIEPS commented Jul 8, 2020

Hello, can you help me for some reason when I download a video that was recorded when opening it does not display the recorded video just a black screen.Also do not tell me how to save videos to server files

@sathiis
Copy link

sathiis commented Aug 3, 2020

Hello sir,when I download a video, the fast forward and backward option in that video is not working. Can you help me ?

@marianamarini
Copy link

This code is fantastic - thank you, Professor!
Question - when I click on the "download" option, only the sound comes up, not the video. Any idea why?
I tried changing the file type to other ones like .mov, and still only the sound comes up.
Thanks for any info.

@LightingSpider
Copy link

Hello, is there any way to capture and record the whole system audio (not input from microphone).

@prof3ssorSt3v3
Copy link
Author

Not on every browser / OS. Thanks Apple.
Try looking at the HTML5 Screen Capture API - https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API

@dmtomas
Copy link

dmtomas commented Mar 16, 2021

Does someone know how to take the audio part of the saved video? I'm using the mediaStreamObj on tensorflowjs and is translating it as empty.
BTW thanks for the audio and video code I don't know how I would have solve that problem jaja.

@eeshanwaqar
Copy link

Any idea on how can i directly download the video when i press stop recording button?

@prof3ssorSt3v3
Copy link
Author

Downloads MUST be initiated by the user. They have to click the anchor with the express intention of downloading a file. This can't be done before the file is generated.

@Ellecus
Copy link

Ellecus commented Jun 18, 2022

i have a problem that i think it might be with my apache settings but i'm not sure, so i use the code you published without editing and it still didn't work for me i didn't event get the notification to use my camera when i refreshed my http://localhost/

@nikhilreddydev
Copy link

I have received the blob at server side using multer.
But

  • type of file in req.file is converted to text/plain

But how do I save it as a video file there?
@prof3ssorSt3v3 please help me sir.

@amankhale
Copy link

@prof3ssorSt3v3 Hey, I'm not able to seek in the HTML video player of chrome browser. Is there any configurations that I need to perform to achieve seeking in the player?

@techGlen
Copy link

Hi
am struggling to store captured video using webcam( js) into file server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment