javascript 如何叠加两个音频文件Node JS FFmpeg

db2dz4w8  于 2023-04-28  发布在  Java
关注(0)|答案(1)|浏览(169)

我的代码只正确工作一次,并且只有在我重新启动我的程序后才开始正确工作。第一次代码输出正确的音频,其中一个叠加在另一个的顶部,第二次只有一个持续时间为15秒的音频。我在尝试获取两个音频文件来帮助Nodejs与FFMPEG你知道怎么修吗?我的代码如下所示。

async songMerge(bg_id, text) {
    const bgMusic = await this.airtable
      .table("BackgroundMusic")
      .select({ view: "View", filterByFormula: `ID = '${bg_id}'` })
      .firstPage();
    if (!bgMusic.length) throw new Error("is not found");

    const result = await fetch(
      `https://api.elevenlabs.io/v1/text-to-speech/VR6AewLTigWG4xSOukaG`,
      {
        method: "POST",
        headers: {
          accept: "audio/mpeg",
          "xi-api-key": "token",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          text,
          voice_settings: {
            stability: 0,
            similarity_boost: 0,
          },
        }),
      }
    );

    const audioBuffer = await result.arrayBuffer();
    const filePath = path.join(__dirname, "../../../", "audio.mp3");

    await fs.writeFileSync(filePath, Buffer.from(audioBuffer));

    const test = await fetch(`${bgMusic[0].fields.AudioLink}`);
    const audioBufferr = await test.arrayBuffer();

    const filePathh = path.join(__dirname, "../../../", "test.mp3");
    await fs.writeFileSync(filePathh, Buffer.from(audioBufferr));

    await mergeAudio(filePathh, filePath);
  }

合并音频功能:

async function mergeAudio(bgMusic, path) {
  return await command
    .addInput(path)
    .addInput(bgMusic)
    .complexFilter([
      {
        filter: "amix",
        inputs: ["0:0", "1:0"],
      },
    ])
    .outputOptions("-y") // add this line to overwrite the output file
    .output(`./overlayed.mp3`)
    .setStartTime("00:00:00")
    .setDuration("15")
    .on("error", function (err) {
      console.log(err);
    })
    .on("end", function () {
      return "ok";
    })
    .run();
}
5m1hhzi4

5m1hhzi41#

答案是每次使用mergeAudio()时创建const command = ffmpeg()

async function mergeAudio(bgMusic, path) {
  const command = ffmpeg();
  const outputFileName = `overlayed-${Date.now()}.mp3`; // Generate a unique file name
  return await command
    .addInput(path)
    .addInput(bgMusic)
    .complexFilter([
      {
        filter: "amix",
        inputs: ["0:0", "1:0"],
      },
    ])
    .output(outputFileName) // Use the generated file name
    .outputOptions("-y") // add this line to overwrite the output file
    .setStartTime("00:00:00")
    .setDuration("15")
    .on("error", function (err) {
      console.log(err);
    })
    .on("end", function () {
      return "ok";
    })
    .run();
}

相关问题