¿Cómo obtengo una instantánea de un video en NodeJS?
-
25-10-2019 - |
Pregunta
Estoy tratando de escribir un servidor NodeJS que tome una entrada de tiempo (posiblemente parte de la ruta de URL) y luego proporcione un marco de video en ese índice de tiempo como una imagen JPEG.
Puedo hacer esto fácilmente en JavaScript simple, pero no puedo ver una manera de hacer esto en NodeJs. Sé que probablemente necesitaré usar un complemento de lienzo como Node-Canvas para hacer la instantánea.
Cualquier idea bienvenida.
Lo siguiente es cómo lo hago en JavaScript en este momento:
myJavaScript.js
function capture(video, scaleFactor) {
if(scaleFactor == null){
scaleFactor = 1;
}
var w = video.videoWidth * scaleFactor;
var h = video.videoHeight * scaleFactor;
stdout("<br/> w: "+ w+ "<br/> h: "+ h);
var canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
var ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, w, h);
return canvas;
}
function shoot(){
var video = document.getElementById("videoTag");
var output = document.getElementById("output");
var canvas = capture(video, 1);
output.innerHTML = '';
output.appendChild(canvas);
}
index.html
<html>
<head>
<title>video snap</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>
<body>
<div id="video_container" >
<video id="videoTag" width="640" height="360" autobuffer="" controls="true">
<source src="frozenplanet.mp4" type="video/mp4">
<source src="frozenplanet.ogv" type="video/ogg">
</video>
</div>
<div id="output"></div>
</body>
</html>
Solución
nodo-fluent-ffmpeg tiene un buen takeScreenshots
función.
var proc = new ffmpeg('/path/to/your_movie.avi')
.takeScreenshots({
count: 1,
timemarks: [ '600' ] // number of seconds
}, '/path/to/thumbnail/folder', function(err) {
console.log('screenshots were saved')
});
Otros consejos
Como 'nodo-fluent-ffmpeg' no funcionó para mí por alguna razón, lo descubrí yo mismo, según el código de videociprisas (que tampoco estaba funcionando para mí). Debe instalar FFMPEG antes de poder usar este código, aquí es un tutorial sobre cómo hacerlo para Mac.
var path = require('path'), // Default node module
pathToFile = path.join(__dirname, 'folder', 'file.mov'),
pathToSnapshot = path.join(__dirname, 'folder', 'file-snapshot.jpg');
// Also a default node module
require('child_process').exec(('ffmpeg -ss 00:00:25 -i ' + pathToFile + ' -vframes 1 -q:v 2 ' + pathToSnapshot), function () {
console.log('Saved the thumb to:', pathToSnapshot);
});
Puedes usar el nodo-fluent-ffmpeg Módulo para esto. Deberá instalar ffmpeg; en macOS, instalar Casería casera Entonces usa el brew install ffmpeg
dominio.
var ffmpeg = require('fluent-ffmpeg');
ffmpeg('/path/to/video.mp4')
.on('end', function() {
console.log('Screenshots taken');
})
.on('error', function(err) {
console.error(err);
})
.screenshots({
// Will take screenshots at 20%, 40%, 60% and 80% of the video
count: 4,
folder: '/path/to/output'
});