客戶(hù)有個(gè)上傳視頻的需求,上傳的視頻呢,需要能在線(xiàn)播放并且列表中必須出現(xiàn)類(lèi)似優(yōu)酷等視頻首頁(yè)上的那種縮略圖,成品如下圖所示:

當(dāng)然了,上傳視頻的界面就不貼出來(lái)了,畢竟我們這篇文章的重點(diǎn)不在于如何上傳,而在于如何用nodejs截取視頻中的幀!~
這里我們需要一個(gè)開(kāi)源的第三方插件----大名鼎鼎的多媒體編解碼框架ffmpeg,需要安裝在服務(wù)器上由nodejs調(diào)用,
代碼貼出如下:
function fecthVideoThumbnail(entryid, index){ var filename = path.join(imageDir, entryid, index + videoSuffix); var thumb = path.join(imageDir, entryid, "overview",index + thumbSuffix); var thumbPath = path.join(imageDir, entryid, "overview"); if (!fs.existsSync(thumbPath)) { <span style="white-space:pre"> </span>fs.mkdirSync(thumbPath); <span style="white-space:pre"> </span>} var that = this; filename = filename.replaceAll("http:////","http:////"); var cmdthumb = thumb.replaceAll("http:////","http:////"); if(!fs.existsSync(thumb)){ exec("ffmpeg -ss 00:00:10 -i "+filename+" -y -f image2 -t 0.001 "+cmdthumb+"", function() { console.log(arguments[0]); console.log('success'); readFileEntry(thumb,that.res); }); }else{ readFileEntry(thumb,that.res); } } function readFileEntry(filename, response) { path.exists(filename, function(exists) { if (!filename || !exists) { response.writeHead(404); response.end(); return; } fs.readFile(filename, "binary", function(err, file) { if (err) { response.writeHead(404); response.end(); return; } var contentType = 'none'; var ext = path.extname(filename); switch (ext) { case ".xml": contentType = 'application/xml;charset=utf-8'; break; case ".json": contentType = 'application/json;charset=utf-8'; break; case ".png": contentType = 'image/png'; break; case ".jpg": contentType = 'image/jpeg'; break; case ".flv": contentType = "video/flv"; break; } response.writeHead(200, { 'Content-Type' : contentType, 'Content-Length' : file.length, 'Accept-Ranges' : 'bytes', 'Server' : 'Microsoft-IIS/7.5', 'X-Powered-By' : 'ASP.NET' }); response.write(file, "binary"); response.end(); }); }); } 重點(diǎn)就是這段
exec("ffmpeg -ss 00:00:10 -i "+filename+" -y -f image2 -t 0.001 "+cmdthumb+"", function() { console.log(arguments[0]); console.log('success'); readFileEntry(thumb,that.res); }); exec函數(shù)可以像cmd DOS命令臺(tái)一樣直接執(zhí)行系統(tǒng)命令,ffmpeg提供的正是這樣的接口。具體的API可以參照f(shuō)fmpeg的文檔,-ss代表指定視頻初始進(jìn)度,-i代表入?yún)⒁曨l文件位置,-y代表Overwrite output files without asking.直接覆蓋已存在文件而不必詢(xún)問(wèn),-t代表截取時(shí)長(zhǎng)(圖片的話(huà)0.001即可),-f代表
-f fmt (input/output)
Force input or output file format. The format is normally auto detected for input files and guessed from the file extension for output files, so this option is not needed in most cases.
強(qiáng)制輸出文件格式,基本上用不到……最后cmdthumb代表輸出文件名。nodejs的exec執(zhí)行完成之后,會(huì)通知回調(diào)函數(shù)。此時(shí)返回生成的縮略圖即可,將此過(guò)程寫(xiě)成rest服務(wù),直接將url填充在img標(biāo)簽的src屬性中即可!
nodejs寫(xiě)這種服務(wù)端程序非常簡(jiǎn)單,方便,輕量。比java要簡(jiǎn)潔得多,并且不需要像tomcat那么麻煩。唯一的缺點(diǎn)可能就是調(diào)試比較麻煩了……
另外,上圖中所示的視頻服務(wù)我也是用nodejs實(shí)現(xiàn)的,效率還不錯(cuò)~
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注