Categories
Vue 3 Projects

Add a Video Player with Vue 3 and JavaScript

Spread the love

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a video player with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create video-player

and select all the default options to create the project.

Create the Video Player

We can create the video player by writing:

<template>
  <video width="320" height="240" ref="videoPlayer">
    <source
      src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4"
      type="video/mp4"
    />
    Your browser does not support the video tag.
  </video>
  <div>
    <button @click="play">play</button>
    <button @click="pause">pause</button>
    <button @click="stop">stop</button>
    <button @click="setSpeed(0.5)">0.5x</button>
    <button @click="setSpeed(1)">1x</button>
    <button @click="setSpeed(1.5)">1.5x</button>
    <button @click="setSpeed(2)">2x</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    play() {
      this.$refs.videoPlayer.play();
    },
    pause() {
      this.$refs.videoPlayer.pause();
    },
    stop() {
      const { videoPlayer } = this.$refs;
      videoPlayer.pause();
      videoPlayer.currentTime = 0;
    },
    setSpeed(speed) {
      this.$refs.videoPlayer.playbackRate = speed;
    },
  },
};
</script>

We have the video element with a ref assigned to it.

width and height sets the dimensions of the video.

The source element has the video source.

We set it to the URL to an MP4 clip that we want to play.

Below that, we add buttons to let us play, pause, and stop the video.

We also have buttons that let us change the playback speed.

Then below that, we add some methods that are called when we click on buttons.

The play method lets us play the video by getting the videoPlayer ref with this.$refs.videoPlayer and calling the play method on the returned video element.

The pause method is similar. We get the videoPlayer ref which has the element and call pause on it to pause the video.

A video element has no method to stop a video. But we can implement that by pausing it and resetting the currentTime to 0.

To set the speed of the video, we can set the playbackRate property.

0.5 is half the normal speed.

And anything above 1 is faster than normal speed.

Conclusion

We can add a video player easily into our web app with Vue 3 and JavaScript.

Leave a Reply

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