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

Vue based on Element button permission implementation solution

Background requirements: The ERP system needs to ...

Several things to note when making a web page

--Homepage backup 1.txt text 2. Scan the image 3. ...

Why MySQL should avoid large transactions and how to solve them

What is a big deal? Transactions that run for a l...

Is a design that complies with design specifications a good design?

In the past few years of my career, I have writte...

MySQL InnoDB transaction lock source code analysis

Table of contents 1. Lock and Latch 2. Repeatable...

Mysql sorting and paging (order by & limit) and existing pitfalls

Sorting query (order by) In e-commerce: We want t...

Sample code for realizing book page turning effect using css3

Key Takeaways: 1. Mastering CSS3 3D animation 2. ...

WeChat applet component development: Visual movie seat selection function

Table of contents 1. Introduction 1. Component da...

Implementation of mysql configuration SSL certificate login

Table of contents Preface 1. MySQL enables SSL co...

MAC+PyCharm+Flask+Vue.js build system

Table of contents Configure node.js+nvm+npm npm s...

Detailed explanation of MySQL EXPLAIN output columns

1. Introduction The EXPLAIN statement provides in...

Drop-down menu and sliding menu design examples

I found a lot of websites that use drop-down or sl...

CSS3 achieves cool sliced ​​image carousel effect

Today we will learn how to use CSS to create a co...