liamappelbe / wav

Dart package for reading and writing wav files
Apache License 2.0
18 stars 5 forks source link

Can I combine multiple wav files into one? #7

Closed khjde1207 closed 1 year ago

khjde1207 commented 1 year ago

Can I combine multiple wav files into one? I want to combine multiple wav files into one. ffmpeg is way too big, so I'm looking for another way.

var wav = await Wav.readFile("$path/tmp0.wav");
var wav1 = await Wav.readFile("$path/tmp1.wav");

wav.channels.addAll(wav1.channels);
await wav.writeFile("$path/all.wav");
print(">>>>>>>>>>>>>>>>>");

I coded like this. The two voices are mingling. Can I merge files from this library?

liamappelbe commented 1 year ago

You're on the right track, your code is just a bit wrong in the details. channels is a 2D array. It's a list of channels, and each channel is a list of samples. What you want to do is append each channel of the second wave to the end of the first wav's corresponding channel. But what you've actually done is just add more channels to an existing wav.

A mono wav file will have 1 channel, and a stereo wav file will have a left and right channel. So I'm guessing what happened is your 2 input wavs are mono, and you combined them into a stereo wav. So one of them will come out of your left speaker, and the other will come out the right.

Instead you should construct a new Wav, and for each channels of the input wavs, make a new Float64List that concatenates the corresponding channel from the 2 inputs.

Something like this (phone coding, may have mistakes ;)

final chan = [];
for (int i = 0; i < wav.channels.length; ++i) {
  chan.add(Float64List.fromList(wav.channels[i] + wav1.channels[i]));
}
final out = Wav(chan, wav.samplesPerSecond, wav.format);

All this assumes that the 2 input wavs have the same number of channels, and the same sample rate, so you might want to add an assert to verify both those things too.

khjde1207 commented 1 year ago

thank you I was able to combine multiple wav files using the logic you gave me.