1、安装npm install @ffmpeg/ffmpeg@0.10.0 @ffmpeg/core@0.9.8 video.js@8.12.0
2、在vue.config.js中devServer配置
headers: {// 如果需要用到ffmpeg确保ShareArrayBuffer能够正常使用,可能会有安全隐患'Cross-Origin-Embedder-Policy': 'require-corp','Cross-Origin-Opener-Policy': 'same-origin',}
3、拷贝下面三个文件到public静态文件夹下
4、创建convert文件
import FFmpeg from "@ffmpeg/ffmpeg";
const { createFFmpeg, fetchFile } = FFmpeg;
const ffmpeg = createFFmpeg({corePath: "/ffmpeg-core.js",log: true
})export const transCode = async (url = "") => {if (!url) {return;}if (!ffmpeg.isLoaded()) {await ffmpeg.load();}ffmpeg.FS('writeFile', 'name', await fetchFile(url));await ffmpeg.run('-i', 'name', 'output.mp4');const data = ffmpeg.FS('readFile', 'output.mp4');return URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }))
}
5、创建播放组件
<script>
import videojs from "video.js";
import "video.js/dist/video-js.css";
import { transCode } from "./convert";
export default {name: "VideoPlayer",props: {height: {default: "100%",},width: {default: "100%",},},data() {return {player: null,options: {autoplay: "muted",controls: true,loop: true,muted: true,poster: "", //播放前加载图片preload: "auto", //是否预加载src: "", //视频地址},};},mounted() {this.init();},methods: {async init() {this.player = videojs(this.$refs.player, this.options);const buffer = await transCode(/**地址 */);this.player.src({type: "video/mp4",src: buffer,});this.player.ready(() => {});},destory() {this.player && this.player.dispose();},},
};
</script>
<template><div class="video-player" :style="{ width, height }"><video class="player video-js vjs-default-skin" ref="player"></video></div>
</template>
<style scoped lang="scss">
.video-player {position: relative;.player {height: 100%;width: 100%;}
}
</style>
注:
1、只能处理小视频,容易造成内存溢出;
2、等待时间较长,不是最优解;