Implementation of breakpoint resume in vue-video-player

Implementation of breakpoint resume in vue-video-player

In a recent project, I needed to implement the function of resuming video playback from breakpoints. As soon as I heard about this function. I was nervous inside...but also a little secretly happy and a little confused. Take the challenge with a learning attitude.

1. Install the plugin

npm install vue-video-player --save

2. Main.js introduces components

import VideoPlayer from 'vue-video-player'
require('video.js/dist/video-js.css')
require('vue-video-player/src/custom-theme.css')
Vue.use(VideoPlayer)

3. Page using components

<el-tree :data="ChapterOptions"
     :props="defaultProps"
     node-key='id'
     highlight-current
     :filter-node-method="filterNode"
     ref="tree"
     default-expand-all
     @node-click="handleNodeClick" />
<video-player ref="videoPlayer"
        class="video-player vjs-custom-skin"
        style="width: 1000px;height: 576px;display: inline-flex"
        :playsinline="true"
        :options="playerOptions"
        @pause="onPlayerPause($event)"
        @ended="onPlayerEnded($event)"
        @play="onPlayerPlay($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @ready="playerReadied"
    />
<script>
import { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import 'vue-video-player/src/custom-theme.css'
import { treeselect } from "@/api//driver/videoChapter";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
 name: "videoPlayer",
 components: { Treeselect, videoPlayer },
 data() {
 return {
  //User information user:{},
  //===============================
  paused: true,
  learningDuration:
  userId: '', //user id
  chapterId:'', //Chapter id
  timeLog: '', //Video viewing time},
 
  playerOptions: {
  playbackRates: [0.5, 1.0, 1.5, 2.0], //Playback speed autoplay: false, // If true, the browser starts playback when it is ready.
  muted: false, // By default any audio will be muted.
  loop: false, // Causes the video to restart as soon as it ends.
  preload: 'auto', // Suggests whether the browser should start downloading video data after the <video> element is loaded. auto The browser chooses the best behavior and starts loading the video immediately (if the browser supports it)
  language: 'zh-CN',
  aspectRatio: '16:9', // Put the player into fluid mode and use this value when calculating the dynamic size of the player. The value should represent a ratio - two numbers separated by a colon (e.g. "16:9" or "4:3").
  fluid: true, // When true, Video.js player will have fluid size. In other words, it will scale proportionally to fit its container.
  sources:
   {
   type: 'video/mp4', // There are many types supported here: basic video format, live broadcast, streaming media, etc. For details, please refer to the git URL project src: ''// url address}
  ],
  hls: true,
  poster: '', // Your cover address width: document.documentElement.clientWidth, // Player width notSupportedMessage: 'This video cannot be played at the moment, please try again later', // Allows you to override the default message displayed when Video.js cannot play the media source.
  controlBar: {
   //The separator between the current time and duration timeDivider: true,
   //Display duration durationDisplay: true,
   //Whether to display the remaining time function remainingTimeDisplay: false,
   //Full screen button fullscreenToggle: true
  }
  }
 };
},
computed: {
 player() {
  return this.$refs.videoPlayer.player //Custom playback}
 },
mounted () {
 this.timer = setInterval(this.putLearningObj, 3000)
 },
destroyed () {
 // If the timer is running, turn it off if (this.timer) {
  clearInterval(this.timer)
  }
 },
methods: {
 //User information getUser() {
  getUserProfile().then(response => {
  this.user = response.data;
  this.learningDuration.userId = this.user.userId
  });
 },
  //============================
 fullScreen() {
  const player = this.$refs.videoPlayer.player
  player.requestFullscreen() //Call the full screen API method player.isFullscreen(true)
  player.play()
 },
 onPlayerPlay(player) {
  this.paused = false
  // player.play()
 },
 onPlayerPause (player) {
  this.paused = true
  // console.log('onPlayerPause!', player)
 },
 onPlayerEnded (player) {
  this.paused = false;
  // clearInterval(this.timer);
 },
 //Triggered when the current playback position changes.
 onPlayerTimeupdate (player) {
  // console.log(' onPlayerTimeupdate!', this.timeLog)
 },
 /* Set the video progress */
 playerReadied: function (player) {
 },
};
</script>

The src video address above can be replaced with a specific address string, or it can be replaced with a background address string. Because mine is a chapter tree, I associated it with the chapter id.

 /** Query department drop-down tree structure*/
 getTreeselect() {
  treeselect().then((response) => {
  //Cover var img = '';
  this.ChapterOptions = response.data;
  for (let i = 0; i < this.ChapterOptions.length ; i++) {
   this.videoName = this.ChapterOptions[0].children[0].chapterName
   this.videoIntroduce = this.ChapterOptions[0].children[0].chapterIntroduce
   this.VideoUrl = JSON.parse(this.ChapterOptions[0].children[0].videoAddress)
   img = JSON.parse(this.ChapterOptions[0].children[0].imageAddress)
   //Initialize the cover for (let j = 0; j <img.length; j++) {
   this.playerOptions.poster =img[0];
   }
   //Initialize the first chapter video for (let j = 0; j <this.VideoUrl.length; j++) {
   this.playerOptions.sources[0].src = this.VideoUrl[0]
   }
   //Initialize chapter this.learningDuration.chapterId = this.ChapterOptions[0].children[0].id;
   //Default highlight first chapter node this.$nextTick(()=>{
   this.$refs.tree.setCurrentKey(this.ChapterOptions[0].children[0].id);
   })
  }
  });
 },
 // Filter node filterNode(value, data) {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
 },
 // Node click event handleNodeClick(data) {
  // console.log(data)
  var img = '';
  //Refresh the original video, original cover this.playerOptions.sources[0].src = '';
  this.playerOptions.poster = '';
  //Convert video this.VideoUrl = JSON.parse(data.videoAddress);
  // console.log("this.VideoUrl")
  for (let i = 0; i < this.VideoUrl.length ; i++) {
  this.playerOptions.sources[0].src = this.VideoUrl[0];
  }
  img = JSON.parse(data.imageAddress);
  for (let i = 0; i < img.length ; i++) {
  this.playerOptions.poster = img[0];
  }
  // console.log("this.playerOptions.sources[0].src")
  // console.log(this.playerOptions.sources[0].src)
  //Chapter introduction this.videoIntroduce = data.chapterIntroduce;
  //Chapter name this.videoName = data.chapterName;
  //Chapter id
  this.learningDuration.chapterId = data.id
  // console.log(this.videoIntroduce)
 },

4. Progress saving

The next step is to save the progress bar of the video. By printing, it is found that onPlayerTimeupdate can get the progress of the video, so a timer is used to trigger data interaction every 3 seconds.

computed: {
 player() {
  return this.$refs.videoPlayer.player //Custom playback}
 },
 mounted () {
 this.timer = setInterval(this.putLearningObj, 3000)
 },
 destroyed () {
 // If the timer is running, turn it off if (this.timer) {
  clearInterval(this.timer)
  }
 },
methods: {  
putLearningObj() {
  if (!this.paused) {
  //Save video progress saveTime(this.learningDuration)
  console.log('putLearningObj ~~~~~~~~~~')
  }
 },
//Triggered when the current playback position changes.
onPlayerTimeupdate (player) {
 this.learningDuration.timeLog = player.cache_.currentTime
  // console.log(' onPlayerTimeupdate!', this.timeLog)
 },
},

saveTime is my custom method for interacting with the backend. (You can define it yourself)

// Save video progress export function saveTime(data) {
 return request({
 url: '/***/****/***/',
 method: 'put',
 data: data
 })
}

At this point, the progress can be saved.

4. Progress recovery

If you want to restore the progress, you must set the saved progress to the video before the video is played. By printing, you can see that playerReadied can be set

/* Set the video progress */
playerReadied: function (player) {
//You can call the background interaction method here...
player.currentTime(this.learningDuration.timeLog)
},

At this point the progress can be restored and you're done! . As the background interaction data requirements are different, the code is not posted.

This is the end of this article about vue-video-player breakpoint resume. For more related vue video player breakpoint resume content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use vue-video-player to achieve live broadcast
  • Tutorial on how to use vue video and vue-video-player to spread videos
  • Detailed explanation of using vue-video-player as a video plugin in vue
  • Detailed configuration of vue-video-player video player
  • Example of using the video plugin vue-video-player in vue
  • How to use the vue-video-player plugin for vue video playback
  • Detailed explanation of vue-video-player usage experience (compatible with m3u8)
  • Implementation of vue-video-player playing m3u8 video stream

<<:  4 Scanning Tools for the Linux Desktop

>>:  Installation tutorial of MySQL 5.7.17 zip package version under win10

Recommend

Let's talk about bitwise operations in React source code in detail

Table of contents Preface Several common bit oper...

Win10 configuration tomcat environment variables tutorial diagram

Before configuration, we need to do the following...

Solution to MySQL master-slave delay problem

Today we will look at why master-slave delay occu...

Detailed explanation of Linux netstat command

Table of contents Linux netstat command 1. Detail...

Linux method example to view all information of the process

There is a task process on the server. When we us...

Docker FAQ

Docker only maps ports to IPv6 but not to IPv4 St...

How to enable MySQL remote connection

For security reasons, MySql-Server only allows th...

How to place large images in a small space on a web page

Original source: www.bamagazine.com There are nar...

Detailed Tutorial on Using xargs Command on Linux

Hello everyone, I am Liang Xu. When using Linux, ...

How to install openjdk in docker and run the jar package

Download image docker pull openjdk Creating a Dat...

Detailed explanation of angular two-way binding

Table of contents Bidirectional binding principle...