Created
February 13, 2020 15:39
-
-
Save rafinskipg/11bb15a13969617e587fa6b2a4c97465 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require('fs') | |
const ffmpeg = require('fluent-ffmpeg') | |
const path = require('path') | |
const FRAMES_PER_SECOND = 30 | |
const framesFolder = path.resolve('myfolder', 'videos', 'frames') | |
function getAllFilesFromFolder(folderPath, extension) { | |
return new Promise((resolve, reject) => { | |
fs.readdir(folderPath, (err, files) => { | |
if(err) { | |
reject(err) | |
} else { | |
resolve(files.map(f => { | |
return { | |
name: f.split('.').slice(0, -1).join('.'), | |
fullPath: path.join(folderPath, f), | |
extension: f.split('.').pop() | |
} | |
}).filter( f => f.extension === extension)) | |
} | |
}) | |
}) | |
} | |
function generateFrames(input, output) { | |
const cmd = ffmpeg(input) | |
.outputOptions('-r ' + FRAMES_PER_SECOND) | |
.on('start', (cmd) => console.log({ cmd })) | |
return new Promise((resolve, reject) => { | |
cmd | |
.on('end', () => resolve(output)) | |
.on('error', (err) => { | |
console.log('failing for ', input, output) | |
reject(err) | |
}) | |
.output(output) | |
.run() | |
}) | |
} | |
function createFoldersForFiles(files) { | |
files.forEach(f => { | |
const filePath = path.resolve(framesFolder, f.name) | |
if (fs.existsSync(filePath)) { | |
console.log('folder already exist... removing') | |
fs.rmdirSync(filePath, { recursive: true }) | |
} | |
fs.mkdirSync(filePath) | |
}) | |
} | |
function generateFramesForFiles(files) { | |
return Promise.all(files.map( f => { | |
const outputPath = path.resolve(framesFolder, f.name, '%0d.jpg') | |
return generateFrames(f.fullPath, outputPath) | |
})) | |
} | |
function execute() { | |
const filePath = path.resolve('videosFolder') | |
console.log('Get all mp4 files') | |
getAllFilesFromFolder(filePath, 'mp4') | |
.then(files => { | |
if (files.length === 0) { | |
console.log('Oops.. we found 0 files') | |
return | |
} | |
console.log('creating folders...') | |
createFoldersForFiles(files) | |
console.log('generating frames for files') | |
generateFramesForFiles(files) | |
.then(() => { | |
console.log('frames generated') | |
}) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
} | |
execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment