bCliks
bCliks

Reputation: 2958

Merge Audio files - node js

I have 2 audio files for primary and background music that I want to merge (not concatenate). The final audio file should be as long as the primary file, and if the background music is shorter then it should repeat.

If there any node js package or a library that can be used to do this?

Upvotes: 6

Views: 12470

Answers (3)

Extender
Extender

Reputation: 260

I used sox-audio, finally with this code:

import SoxCommand from "sox-audio";
const TimeFormat = SoxCommand.TimeFormat;

export const merge = async (audio, music, audioSeconds, output) => {
    try {
        const command = SoxCommand();
        const endTime = TimeFormat.formatTimeAbsolute(audioSeconds);
        command.input(audio).inputFileType("mp3"); 
        const trimMusic = SoxCommand().input(music).output("-p").outputFileType("mp3").trim(0, endTime);
        command.inputSubCommand(trimMusic).output(output).outputFileType("mp3").combine("merge");
        return new Promise((resolve, reject) => {
            command.on("error", function (err, stdout, stderr) {
                console.log("Cannot process audio: " + err.message);
                console.log("Sox Command Stdout: ", stdout);
                console.log("Sox Command Stderr: ", stderr);
                resolve(null);
            });
            command.on("end", function () {
                console.log("Sox command succeeded!");
                resolve(true);
            });
            command.run();
        });
    } catch (error) {
        console.error(error);
        return null;
    }
};

Upvotes: 1

Ahmad Zahabi
Ahmad Zahabi

Reputation: 1268

Check this https://www.npmjs.com/package/sox-audio

combine(method) Select the input file combining method, which can be one of the following strings: 'concatenate' 'sequence' 'mix' 'mix-power' 'merge' 'multiply'

or use this if you need a simpler one https://github.com/ttippin84/audio-combiner

Upvotes: 1

Tibor Szasz
Tibor Szasz

Reputation: 3227

SOX is a good utility to do audio manipulation: http://sox.sourceforge.net/

There are node wrappers for it:

https://github.com/andrewrk/node-sox

https://github.com/substack/node-sox

Upvotes: 4

Related Questions