在 Express.js 中使用 ffmpeg 合并视频和音频

问题描述 投票:0回答:1

我在 Express 服务器中使用 FFmpeg-static 来合并来自 Youtube Readable Stream 的音频和视频。我在一个 Github 存储库上找到了一段代码,但该代码正在转换并直接保存到后端根文件夹。我想要的是合并,然后将其直接pipe发送给最终用户。 我找到的代码如下:

router.get('/try', async (req, res)=>{
let vid = ytdl(ytvideoUrl, {filter: format => format.qualityLabel === '144p'})
let aud = ytdl(ytvideoUrl, { quality: 'lowestaudio' })

const ffmpegProcess = cp.spawn(ffmpeg, [
    '-loglevel', '8', '-hide_banner',
    '-progress', 'pipe:3',
    '-i', 'pipe:4',
    '-i', 'pipe:5',
    '-map', '0:a',
    '-map', '1:v',
    '-c:v', 'copy',
    `videoTitle.mp4`,
  ], {
    windowsHide: true,
    stdio: [
      'inherit', 'inherit', 'inherit',
      'pipe', 'pipe', 'pipe',
    ],
  })
ffmpegProcess.on('close', () => {
console.log("Merging Completed");
})
  
aud.pipe(ffmpegProcess.stdio[4]);
vid.pipe(ffmpegProcess.stdio[5]);
})

依赖项是:

const cp = require('child_process');
const ytdl = require('ytdl-core')
const ffmpeg = require('ffmpeg-static');
node.js express ffmpeg encoding ytdl
1个回答
1
投票

你可以试试这个方法

const express = require('express');
const cors = require('cors');
const ytdl = require('ytdl-core');
const app = express();
const cp = require('child_process');
const ffmpeg = require('ffmpeg-static');
const fs = require('fs')
const readline =require('readline')
app.use(express.static(__dirname + "\\static"));
app.use('/static', express.static('./static'));

app.listen(3000, () => {
    console.log("It Works!");
});

app.get('/download', async (req, res) => {
    var url = req.query.url;


    res.header("Content-Disposition", `attachment;  filename=video.mp4`)
    let video = ytdl(url, {
        filter: 'videoonly'
    })
    let audio = ytdl(url, {
        filter: 'audioonly',
        highWaterMark: 1 << 25
    });
    const ffmpegProcess = cp.spawn(ffmpeg, [
        '-i', `pipe:3`,
        '-i', `pipe:4`,
        '-map', '0:v',
        '-map', '1:a',
        '-c:v', 'copy',
        '-c:a', 'libmp3lame',
        '-crf', '27',
        '-preset', 'veryfast',
        '-movflags', 'frag_keyframe+empty_moov',
        '-f', 'mp4',
        '-loglevel', 'error',
        '-'
    ], {
        stdio: [
            'pipe', 'pipe', 'pipe', 'pipe', 'pipe',
        ],
    });

    video.pipe(ffmpegProcess.stdio[3]);
    audio.pipe(ffmpegProcess.stdio[4]);
    ffmpegProcess.stdio[1].pipe(res);

    let ffmpegLogs = ''

    ffmpegProcess.stdio[2].on(
        'data',
        (chunk) => {
            ffmpegLogs += chunk.toString()
        }
    )

    ffmpegProcess.on(
        'exit',
        (exitCode) => {
            if (exitCode === 1) {
                console.error(ffmpegLogs)
            }
        }
    )
});

© www.soinside.com 2019 - 2024. All rights reserved.