Categories
JavaScript Answers

How to play local (hard-drive) video file with HTML5 video tag with JavaScript?

Spread the love

You can play a local video file using the HTML5 <video> tag along with JavaScript. Here’s how you can do it:

1. HTML Structure

Add a <video> tag to your HTML file. You’ll need to specify the src attribute with the path to your local video file.

```html
<video id="myVideo" width="320" height="240" controls>
    <source src="path_to_your_video.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>
```
</code></pre>
<h3>2. JavaScript</h3>
<p>You can control the video playback using JavaScript. For example, you can play, pause, or adjust the playback rate.</p>
<pre><code>```html
<script>
    const video = document.getElementById('myVideo');

    function playVideo() {
        video.play();
    }

    function pauseVideo() {
        video.pause();
    }

    function setPlaybackRate(rate) {
        video.playbackRate = rate;
    }
</script>
```
</code></pre>
<h3>3. Event Handling</h3>
<p>You can also handle various events of the <code><video></code> element, such as <code>play</code>, <code>pause</code>, <code>ended</code>, etc., to perform certain actions.</p>
<pre><code>```html
<script>
    video.onplay = function() {
        console.log("Video is playing");
    };

    video.onpause = function() {
        console.log("Video is paused");
    };

    video.onended = function() {
        console.log("Video has ended");
    };
</script>
```

Remember to replace "path_to_your_video.mp4" with the actual path to your local video file.

Also, make sure that the video file is in a format supported by the <video> tag (e.g., MP4, WebM, Ogg).

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *