Creating a Real-Time Camera Stream Application using js

mdshamsfiroz
4 min readOct 17, 2024

--

In today’s digital age, live streaming has become an integral part of many web applications. Whether you’re building a video chat app, a virtual photobooth, or just experimenting with web technologies, knowing how to implement a live camera stream using JavaScript is a valuable skill. In this blog post, we’ll walk through the process of creating a simple yet functional live camera stream application using HTML, CSS, and JavaScript.

Setting Up the HTML Structure

First, let’s look at the HTML structure of our application:

<h1>Live Camera Stream</h1>
<video id="videoElement" autoplay playsinline></video>
<div>
<button id="startButton">Start Stream</button>
<button id="stopButton">Stop Stream</button>
</div>

This structure includes a title, a video element to display the stream, and two buttons to control the stream.

Styling with CSS

We’ve added some basic CSS to make our application more visually appealing:

body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
#videoElement {
width: 100%;
max-width: 640px;
height: auto;
border: 1px solid #ddd;
margin-bottom: 20px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 0 10px;
cursor: pointer;
}

This CSS centers the content, sets a maximum width for the video, and styles the buttons for better user interaction.

Implementing the JavaScript Functionality

Now, let’s break down the JavaScript code that powers our live stream:

  1. Accessing DOM Elements:
const videoElement = document.getElementById('videoElement');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
let stream;
  1. Starting the Stream:
async function startStream() {
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'user' // Use 'environment' for rear camera
},
audio: false
});
videoElement.srcObject = stream;
startButton.disabled = true;
stopButton.disabled = false;
} catch (err) {
// Error handling...
}
}

This function uses the getUserMedia API to access the device's camera. We're requesting video only (no audio) and using the front-facing camera by default.

  1. Stopping the Stream:
function stopStream() {
if (stream) {
const tracks = stream.getTracks();
tracks.forEach(track => track.stop());
videoElement.srcObject = null;
startButton.disabled = false;
stopButton.disabled = true;
}
}

This function stops all tracks of the stream and resets the video element.

  1. Event Listeners:
startButton.addEventListener('click', startStream);
stopButton.addEventListener('click', stopStream);
window.addEventListener('beforeunload', stopStream);

These listeners handle button clicks and ensure the stream is stopped when the page is unloaded.

Error Handling

We’ve implemented basic error handling to inform the user if there are issues accessing the camera:

if (err.name === 'NotAllowedError') {
alert("Camera access denied. Please allow camera access to use this feature.");
} else {
alert("An error occurred while trying to access the camera: " + err.message);
}
console.error("Error accessing the camera:", err);

Github Code Link:- https://github.com/mdshamsfiroz/Arth-4-Tasks/blob/main/FullStack/Task3.html

Whole Complete Code:-

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Camera Stream</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
padding: 20px;
}
#videoElement {
width: 100%;
max-width: 640px;
height: auto;
border: 1px solid #ddd;
margin-bottom: 20px;
}
button {
font-size: 16px;
padding: 10px 20px;
margin: 0 10px;
cursor: pointer;
}
</style>
</head>
<body>
<h1>Live Camera Stream</h1>
<video id="videoElement" autoplay playsinline></video>
<div>
<button id="startButton">Start Stream</button>
<button id="stopButton">Stop Stream</button>
</div>

<script>
const videoElement = document.getElementById('videoElement');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
let stream;

async function startStream() {
try {
stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'user' // Use 'environment' for rear camera
},
audio: false
});
videoElement.srcObject = stream;
startButton.disabled = true;
stopButton.disabled = false;
} catch (err) {
if (err.name === 'NotAllowedError') {
alert("Camera access denied. Please allow camera access to use this feature.");
} else {
alert("An error occurred while trying to access the camera: " + err.message);
}
console.error("Error accessing the camera:", err);
}
}

function stopStream() {
if (stream) {
const tracks = stream.getTracks();
tracks.forEach(track => track.stop());
videoElement.srcObject = null;
startButton.disabled = false;
stopButton.disabled = true;
}
}

startButton.addEventListener('click', startStream);
stopButton.addEventListener('click', stopStream);

// Optional: Start stream automatically when the page loads
// window.addEventListener('load', startStream);

// Ensure stream is stopped when the page is unloaded
window.addEventListener('beforeunload', stopStream);
</script>
</body>
</html>

Output UI Interface:-

Conclusion

This simple implementation demonstrates how to create a live camera stream using JavaScript. It covers the basics of accessing the device camera, displaying the stream, and handling user interactions. Remember, this code should be run on a secure context (HTTPS or localhost) due to browser security policies. Also, always be mindful of user privacy and provide clear instructions about camera usage in your application.

So, whether you’re a tech enthusiast, a professional, or just someone who wants to learn more, I invite you to follow me on this journey. Subscribe to my blog and follow me on social media to stay in the loop and never miss a post.

Together, let’s explore the exciting world of technology and all it offers. I can’t wait to connect with you!”

Connect me on Social Media: https://linktr.ee/mdshamsfiroz

Happy coding! Happy learning!

--

--

mdshamsfiroz
mdshamsfiroz

Written by mdshamsfiroz

Trying to learn tool by putting heart inside to make something

No responses yet