Pergunta

I have tried mixing two wav files using NAudio library. I was able to get a mixed wav file if they have the same bit rate. My concern here is about mixing wav files of different bit rate. Please suggest if it possible with NAudio, or some other API/Library.

Given below my code for mixing wav files of same bit rate :

  using (var reader1 = new WaveFileReader(inpFile1))
        using (var reader2 = new WaveFileReader(inpFile1))
        {
            var inputs = new List<ISampleProvider>() {
             reader1.ToSampleProvider(),
             reader2.ToSampleProvider(),
        };
            var mixer = new MixingSampleProvider(inputs);
            WaveFileWriter.CreateWaveFile16(outputFile, mixer);
        }
Foi útil?

Solução

I assume you're trying to mix multiple files of a different sample rate. Here's how you can do it with NAudio (I'm using the MediaFoundationResampler, but there are other ways of resampling)

var paths = new[] {
    @"input1.wav",
    @"input2.wav",
    @"input3.wav"
};

// open all the input files
var readers = paths.Select(f => new WaveFileReader(f)).ToArray();

// choose the sample rate we will mix at
var maxSampleRate = readers.Max(r => r.WaveFormat.SampleRate);

// create the mixer inputs, resampling if necessary
var mixerInputs = readers.Select(r => r.WaveFormat.SampleRate == maxSampleRate ?
    r.ToSampleProvider() :
    new MediaFoundationResampler(r, WaveFormat.CreateIeeeFloatWaveFormat(maxSampleRate, r.WaveFormat.Channels)).ToSampleProvider());

// create the mixer
var mixer = new MixingSampleProvider(mixerInputs);

// write the mixed audio to a 16 bit WAV file
WaveFileWriter.CreateWaveFile16(@"d:\mixed.wav", mixer);

// clean up the readers
foreach(var reader in readers)
{
    reader.Dispose();
}

Note that this won't deal with a mixture of mono and stereo input files. In that case, you'd need to also convert mono inputs to stereo (e.g. using MonoToStereoSampleProvider).

Outras dicas

I suggest you to first choose which sample rate value to keep, and resample the other one. Resampling could add distortion if the sample rate change ratio is not a integer.

To resample wav file in C#, please see these posts

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top