Web Real-Time Communication (WebRTC) is an open-source project that enables real-time communication between web browsers and mobile applications. One of the most popular use cases of WebRTC is to project a camera to a web browser. This tutorial will explore the steps required to launch a camera feed to a web browser using WebRTC.
Set up a local server
We'll start by creating a new folder and navigating to it.
mkdir webrtc-demo
cd webrtc-demo
Next, we'll initialize a new npm project inside this directory.
npm init -y
And open that folder inside Visual Studio Code.
code .
We'll need a web server to run our application. We'll use the lite-server package for this.
npm install --save-dev lite-server
Next, We'll create an index.html file inside the root of the webrtc-demo directory that the lite-server will serve.
Also, let's add a script inside our package.json file to run the lite-server.
"scripts": {
"start": "lite-server"
},
Now, let's return to the command prompt to serve our index.html using the following command.
npm start
Once you run this command, your server will be served at port 3000. And you'll be able to access the application at http://localhost:3000.
You'll be presented with a blank screen on this page since the index.html file we added has no content.
Create a simple HTML file
Let's add a basic HTML structure to this file.
<!DOCTYPE html>
<html>
<head>
<title>WebRTC Camera Projection</title>
</head>
<body>
<video style="height: 400; width: 400px;" id="localVideo" autoplay muted></video>
<script src="app.js"></script>
</body>
</html>
This HTML file includes a video element displaying the camera feed and a script element running our JavaScript code.
Set up WebRTC
Next, let's create the app.js file in the root of the webrtc-demo folder and add the following code.
const localVideo = document.getElementById("localVideo");
navigator.mediaDevices.getUserMedia({
video: true
}).then(stream => {
localVideo.srcObject = stream;
}).catch(error => {
console.error("Failed to get user media", error);
});
This JavaScript code retrieves the local camera stream using the "getUserMedia" method provided by the "mediaDevices" object. The stream is then assigned to the "srcObject" property of the video element, which displays the camera feed in the web browser.
And we're done! Next, let's go back to http://localhost:3000 URL and reload the page.
WebRTC will ask you for permission to access the camera as soon as the page loads.
Click on Allow to grant access.
And if you've done everything correctly, you'll see your camera feed inside your web page.
The source code for this project is attached to this article inside the source.zip file.
I hope you enjoyed this post. If you've any queries or feedback, feel free to comment or reach out to me on Twitter @harshalslimaye.