Webserver

如何從nodejs中的遠端影片url下載部分內容?

  • February 12, 2021

我有以下程式碼使用nodejs http.get()下載影片的特定部分(範圍),

const fileUrl = 'https://www.example.com/path/to/video.mp4'
const fs = require('fs')
const http = require('https')
const fileName = 'video.mp4'
const options = {
hostname: 'https://www.example.com',
path: '/path/to/video.mp4',
method: 'GET',
headers: {
'range': 'bytes=0-444444', //the size I'm requesting is the first 444.4 kB of the video
}

const req = http.get(options)
req.on('response', (res) => {
console.log(res.headers) //just to see headers
})

req.on('response', (res) => {
let file = fs.createWriteStream(fileName)
let size
res.on('data', (chunk) => {
file.write(chunk)
size = fs.statSync(file.path).size
console.log(size)
})
})

問題是當我將'range'header設置'range': 'bytes=0-anyValue'為下載的影片時可以正常播放,但是當我設置'range''range': 'bytes=[anyValue>0]-anyValue'下載的影片時損壞並且無法播放。

'range': 'bytes=0-anyValue'傳入的響應標頭是:

{

'content-length': '444445',

'content-range': 'bytes 0-444444/17449469',

'accept-ranges': 'bytes',

'last-modified': 'Tue, 07 May 2019 11:45:38 GMT',

etag: '"f13a255d30ef81d2abf8ba2e4fefc2fd-1"',

'x-amz-meta-s3cmd-attrs': 'md5:4e3127acff74ac20b52e1680a5e0779d',

'cache-control': 'public, max-age=2592000',

'content-disposition': 'attachment; filename="Rim.Of.The.World.2019.720p.Trailer.mp4";',

'content-encoding': 'System.Text.UTF8Encoding',

'x-amz-request-id': 'tx0000000000000001bfccc-00602060b1-1b3f92b-default',

'content-type': 'application/octet-stream',

date: 'Sun, 07 Feb 2021 21:50:41 GMT',

connection: 'close'

}

並且下載的影片可以播放

但是當'range': 'bytes=[anyValue>0]-anyValue傳入的響應標頭是

{

'content-length': '443890',

'content-range': 'bytes 555-444444/17449469',

'accept-ranges': 'bytes',

'last-modified': 'Tue, 07 May 2019 11:45:38 GMT',

etag: '"f13a255d30ef81d2abf8ba2e4fefc2fd-1"',

'x-amz-meta-s3cmd-attrs': 'md5:4e3127acff74ac20b52e1680a5e0779d',

'cache-control': 'public, max-age=2592000',

'content-disposition': 'attachment; filename="Rim.Of.The.World.2019.720p.Trailer.mp4";',

'content-encoding': 'System.Text.UTF8Encoding',

'x-amz-request-id': 'tx00000000000000e8c5225-006020613d-1afef1a-default',

'content-type': 'application/octet-stream',

date: 'Sun, 07 Feb 2021 21:53:01 GMT',

connection: 'close'

}

並且下載的影片已損壞且無法播放

我做錯了什麼?

以及如何正確實現我的目標?

提前致謝。

您可以使用 ffmpeg 命令行工具執行您所要求的操作,如下所示:

ffmpeg -ss [start timestamp] -i [video path or url] -t [duation] [outputname.mp4] or other format

在您的情況下,在 nodejs 中您應該使用fluent-ffmpeg模組:

const ffmpeg = require('fluent-ffmpeg')
const url = 'www.example.com/video.mp4'

ffmpeg(url).seekInput(30)      //cut from the first 30th second
       .duration(10)          //duration I want to cut 
       .output('video.mp4)    //output video name
       .run()                 //run the process

引用自:https://unix.stackexchange.com/questions/633412