vue实现视频剪切
Vue 实现视频剪切的方法
使用 video.js 和 ffmpeg.js 实现前端视频剪切
安装必要的依赖包:
npm install video.js ffmpeg.js
在 Vue 组件中引入相关库:
import videojs from 'video.js';
import { createFFmpeg, fetchFile } from '@ffmpeg/ffmpeg';
初始化 video.js 播放器:

mounted() {
this.player = videojs(this.$refs.videoPlayer, {
controls: true,
autoplay: false,
preload: 'auto'
});
}
实现视频剪切功能:
async cutVideo(startTime, endTime) {
const ffmpeg = createFFmpeg({ log: true });
await ffmpeg.load();
const inputFile = this.$refs.fileInput.files[0];
ffmpeg.FS('writeFile', 'input.mp4', await fetchFile(inputFile));
await ffmpeg.run('-i', 'input.mp4', '-ss', startTime, '-to', endTime,
'-c', 'copy', 'output.mp4');
const data = ffmpeg.FS('readFile', 'output.mp4');
const url = URL.createObjectURL(new Blob([data.buffer], { type: 'video/mp4' }));
this.downloadUrl = url;
this.showDownload = true;
}
使用 Web API 实现简单剪切
利用 MediaSource API 实现基础剪切:

handleFileSelect(event) {
const file = event.target.files[0];
const videoURL = URL.createObjectURL(file);
this.videoSrc = videoURL;
}
cutVideo() {
const video = this.$refs.videoElement;
const start = this.startTime;
const end = this.endTime;
video.currentTime = start;
video.addEventListener('timeupdate', () => {
if (video.currentTime >= end) {
video.pause();
}
});
}
后端处理方案
对于大文件或复杂操作,建议使用后端处理:
前端上传视频和时间参数:
async uploadForCutting() {
const formData = new FormData();
formData.append('video', this.selectedFile);
formData.append('start', this.startTime);
formData.append('end', this.endTime);
const response = await axios.post('/api/cut-video', formData, {
responseType: 'blob'
});
this.resultVideo = URL.createObjectURL(response.data);
}
Node.js 后端示例:
const ffmpeg = require('fluent-ffmpeg');
const express = require('express');
const fileUpload = require('express-fileupload');
app.post('/api/cut-video', (req, res) => {
const { start, end } = req.body;
const video = req.files.video;
ffmpeg(video.tempFilePath)
.setStartTime(start)
.setDuration(end - start)
.output('output.mp4')
.on('end', () => {
res.download('output.mp4');
})
.run();
});
注意事项
- 前端处理受限于浏览器性能和文件大小
- 复杂操作建议使用后端处理
- 考虑添加进度指示器改善用户体验
- 注意跨浏览器兼容性问题
以上方法提供了从简单到复杂的视频剪切实现方案,可根据项目需求选择合适的实现方式。






