Skip to main content

Command Palette

Search for a command to run...

How to Live Stream Your Camera Using JavaScript

Published
2 min read

Live streaming from a camera using JavaScript is an exciting way to enhance web applications, enabling features like video conferencing, online tutorials, or live events. In this blog post, we'll walk through the steps needed to access your device's camera and stream video directly to a web page using the MediaStream API.

1. Setting Up the HTML Structure

First, we need a basic HTML structure. This will include a video element to display the live stream and a button to start streaming.

<!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>
</head>
<body>
    <h1>Live Camera Stream</h1>
    <video id="video" width="640" height="480" autoplay></video>
    <button id="startButton">Start Stream</button>
    <script src="script.js"></script>
</body>
</html>

2. Writing the JavaScript Code

Next, we need to write the JavaScript that will handle accessing the camera and streaming the video.

const video = document.getElementById('video');
const startButton = document.getElementById('startButton');

startButton.addEventListener('click', async () => {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        video.srcObject = stream;
    } catch (error) {
        console.error('Error accessing camera: ', error);
    }
});

3. Understanding the Code

  • navigator.mediaDevices.getUserMedia(): This API requests access to the user's media devices, such as a camera or microphone. We specify that we want video in our options.

  • video.srcObject: Once we receive the stream, we set the video element's source to the stream, allowing the live feed to display in the browser.

4. Testing Your Stream

To test the stream, open your HTML file in a web browser that supports the MediaStream API (like Chrome or Firefox). Click the "Start Stream" button, and you should see your camera feed appear in the video element.

5. Conclusion

Streaming live video using JavaScript is straightforward with the MediaStream API. This technique can be used for various applications, from video chats to monitoring and broadcasting live events. As you enhance your app, consider adding controls for stopping the stream, taking snapshots, or adjusting settings.

For a more detailed guide and additional features, check out the complete documentation on the MDN Web Docs.

More from this blog

Amazon S3 Storage Classes

43 posts