Video.js的使用

Video.js是一款优秀的HTML5视频播放器库,与另一个主流的视频播放器库Shaka Player相比,它在PC端更加流行,也更适用于高度定制化的场景。不过Shaka Player更适合移动端和低带宽场景,小伙伴们在选择库的时候可以根据自己的场景。这里分享一些Video.js使用的经验。

背景:Nuxt 3.3.3,video.js@8.0.4

入门

安装

npm i video.js

写一个公共组件

<template>
	<video ref="videoPlayer" class="video-js" :id="playerId"></video>
</template>

<script setup>
	import videojs from 'video.js';
	import {
		getCurrentInstance,
	} from 'vue';
	const {
		proxy
	} = getCurrentInstance();
	const props = defineProps({
		sources: {
			type: Array,
			default () {
				return [];
			}
		},
		autoplay: {
			type: [Boolean, String],
			default: true,
		},
		playerId: {
			type: String,
			required: true, // 必须提供id
		},
		muted: {
			type: Boolean,
			default: false,
		}
	})

	let videoOptions = {
		'autoplay': props.autoplay, // 自动播放
		'sources': props.sources,
		'loop': true, // 循环
		'muted': props.muted,
		'preload': 'metadata', // 预加载内容
	}

    const player = ref(null);
	onMounted(() => {
		player.value = videojs(proxy.$refs.videoPlayer, videoOptions, () => {
			//player.value.log('onPlayerReady');
		});
	})

	onBeforeUnmount(() => {
		if (player.value) {
			player.value.dispose();
		}
	})

在使用该组件时,通过sources传入视频地址即可。

需要注意的是,playerId是必传的,后续关于视频的操作都需要用到playerId。

获取视频时长

假设template有这个组件

<video-player :sources="sources" :player-id="playerId" />

可以这样写获取视频时长duration,单位秒。

<script setup>
	import videojs from 'video.js';
	const playerId = "playerId ";
    // 视频资源
	const sources = [{
		src: URL.createObjectURL(fileList.value),
		type: 'video/mp4'
	}];
    // 需要在onMounted执行
	onMounted(() => {
		const player = videojs(playerId);
		player.on('loadedmetadata', () => {
			const duration = player.duration();
			console.log(duration);
		})
	})
</script>