如何编辑和拼接视频

How to edit and concatenation video

有没有一种方法可以通过一些脚本将我们预定义的自己的视频剪辑添加到现有视频中,然后将其另存为一个视频?我们不想使用任何视频编辑软件的请让我知道您有任何视频编辑和拼接视频的方法吗?

欢迎光临! ffmpeg is my favorite way of working with audio and video files through code and can be used with most any scripting language (I have done it with python and javascript). There is already an answer to the question here不过我再举个例子。

由于您标记了 javascript 和 node.js,这里是我用来以编程方式(通过代码)完成此操作的代码片段,而无需使用视频编辑器。我在 linux、mac 和 windows 上使用过它,因此文件路径取决于您的系统。它适用于大多数主要的音频和视频格式,但为了本示例,我使用的是 .mp4。我刚刚测试了我在 Windows 10 上发布的这个确切设置,它没有错误。

首先,创建一个新的节点项目(如果您还没有这样做的话)

npm init

接下来,使用 npm 从命令行为节点安装 ffmpeg(这将为任何平台安装它:linux、osx、windows) npm package

npm install ffmpeg-downloader

有多种组合视频的方法,但我喜欢下面的方法。为了合并文件,您需要在 .txt 文件中列出完整的文件路径,每行一个视频文件,ffmpeg 将读取合并(我称我的 files.txt 但它可以被称为任何东西)。我不确定您可以拥有多少个视频,但我已经将最多 15 个视频一次组合成一个最终视频,没有任何问题。

files.txt的内容看起来像这样;您可以根据需要预先创建或通过代码创建它:

file 'C:\path\to\file1.mp4'
file 'C:\path\to\file2.mp4'
file 'C:\path\to\file3.mp4'
file 'C:\path\to\file4.mp4'

现在,在 javascript 文件中(我将我的命名为 combine.js),您可以调整以下内容以适合您的文件路径结构。

const { exec } = require('child_process');
const ffmpeg = require('ffmpeg-downloader');

function combineVideos() {
    console.log('process starting');

    // executable for ffmpeg
    const exe = ffmpeg.path;

    // the files.txt that contains the list of files to combine
    const filesList = 'C:\path\to\files.txt';

    // where you want the final video to be created
    const outFile = 'C:\path\to\finalCombinedVideo.mp4';

    // build the command that ffmpeg will run. It will look something like this:
    // ffmpeg -y -f concat -safe 0 -i "path/to/files.txt" -c copy "path/to/finalCombinedVideo.mp4"

    const cmd = '"' + exe + '" -y'
        + ' -f concat'
        + ' -safe 0'
        + ' -i "' + filesList + '"'
        + ' -c copy "' + outFile + '"';

    exec(cmd, (err, stdout, stderr) => {
        if (err) {
            console.error(`exec error: ${err}`);
            return;
        }

        console.log(`process complete: ${outFile}`);
    });
}

// call the combineVideos function
combineVideos();

现在,您可以使用 node 运行 合并功能并创建视频

node combine.js
process starting
process complete:  C:\path\to\finalCombinedVideo.mp4

希望对您有所帮助。祝你好运!