rochars / wavefile

Create, read and write wav files according to the specs. :star: :notes: :heart:
MIT License
226 stars 48 forks source link

How to concat two wav files? #14

Closed Julyyq closed 5 years ago

Julyyq commented 5 years ago

I wanna merge multiple Wav files to one, can I use this library to handle this?

rochars commented 5 years ago

The current version of wavefile does not support this. I will add this to the roadmap for a future release. Thanks!

jlucaso1 commented 4 months ago

I got this working with the following code (i'm using Bun but works with node too):

import { WaveFile } from "wavefile";

const audio1 = await Bun.file("hello.wav").arrayBuffer();
const audio2 = await Bun.file("world.wav").arrayBuffer();

const mergedAudio = mergeAudio(audio1, audio2);

await Bun.write("merged.wav", mergedAudio);

function mergeAudio(audio1: ArrayBuffer, audio2: ArrayBuffer) {
  const a = new WaveFile(new Uint8Array(audio1));
  const b = new WaveFile(new Uint8Array(audio2));

  const aSamples = a.getSamples();
  const bSamples = b.getSamples();

  const mergedSamples = new Float64Array(aSamples.length + bSamples.length);

  mergedSamples.set(aSamples);
  mergedSamples.set(bSamples, aSamples.length);

  const newWaveFile = new WaveFile();

  newWaveFile.fromScratch(1, 24000, "16", mergedSamples);

  return newWaveFile.toBuffer();
}