nodejs+ffmpeg

Mac或linux环境下使用ffmpeg工具+ffmpeg库

  1. 本地下载ffmpeg命令行程序
  2. 安装node ffmpeg库
npm install ffmpeg
  1. 实现视频操作类
//ffmpeg 操作类
const ffmpeg = require('ffmpeg')

module.exports = class FFMPEGOperation {
    constructor() {
        
    }
    //获取视频时长
    getVideoTotalDuration(videoPath) {
        const process = new ffmpeg(videoPath)
        return process.then(function (video) {
            console.log('getVideoTotalDuration,seconds:' + video.metadata.duration.seconds)
            return video.metadata.duration.seconds || 0
        }, function (err) {
            console.log('getVideoTotalDuration,err:' + err.message)
            return -1
        })
    }
    //获取视频缩略图
    getVideoSceenshots(videoPath, outPutPath, frameRate, frameCount){
        const process = new ffmpeg(videoPath);
        return process.then(function (video) {
            video.fnExtractFrameToJPG(outPutPath, {
                frame_rate : frameRate,
                number : frameCount,
                file_name : 'my_frame_%t_%s'
            }, function (error, files) {
                if (!error)
                    console.log('Frames: ' + files)
            })
        }, function (err) {
            console.log('Error: ' + err)
        })
    }
    //拆分视频
    splitVideo(videoPath, startTime, duration, outVideoPath){
        const    process = new ffmpeg(videoPath)
        return process.then(function (video) {
            video
            .setVideoStartTime(startTime)
            .setVideoDuration(duration)
            .save(outVideoPath, function (error, file) {
                if (!error){
                    console.log('Video file: ' + file)
                 }
            })
        }, function (err) {
            console.log('Error: ' + err)
        })
    }
}
  1. 调用
//ffmpeg
const main = async () => {
  const FFMPEGOperation = require('./ffmpeg_op')
  const FFMPEGOperationObj = new FFMPEGOperation()
  const videoPath = './input/test.mp4'
  const outputPath = './output/'
  //获取视频时长
  const duration = await FFMPEGOperationObj.getVideoTotalDuration(videoPath)
  console.log(duration)
  //获取缩略图
  await FFMPEGOperationObj.getVideoSceenshots(videoPath,outputPath,1,5)
  //拆分视频
  await FFMPEGOperationObj.splitVideo(videoPath,100,10,outputPath+'splitResult.mp4')
}
main().then().catch(console.error)

你可能感兴趣的:(nodejs+ffmpeg)