Faris Zacina
Faris Zacina

Reputation: 14274

NAudio - Changing Bitrate of Recorded WAV file

i am trying to implement audio recording using NAudio to a Wav file, but the default bitrate set by the WasapiLoopbackCapture class can't be changed programmatically.

I am recording the audio output to a MemoryStream (recordedStream in snippet below). However the default bitrate set by the WasapiLoobpackCapture doesn't fit my needs.

I would like to have a bit rate of 320KBPS and i tried to convert the recorded file programmatically using the WaveFormatConversionStream class, but i couldn't make it work.

 WaveFormat targetFormat = WaveFormat.CreateCustomFormat(waveIn.WaveFormat.Encoding,
                                                                waveIn.WaveFormat.SampleRate, //SampleRate
                                                               waveIn.WaveFormat.Channels,     //Channels
                                                              320000,    //Average Bytes per Second
                                                               waveIn.WaveFormat.BlockAlign,     //Block Align
                                                                waveIn.WaveFormat.BitsPerSample);    //Bits per Sample   


        using (WaveStream inputStream = new RawSourceWaveStream(recordedStream, waveIn.WaveFormat))
        {
            try
            {
                using (var converter = new WaveFormatConversionStream(targetFormat, inputStream))
                {
                    // ...
                }
            }
            catch (Exception)
            {
                throw;
            }

            recordedStream.Dispose();
        }

I always get an "AcmNotPossible calling acmStreamOpen" conversion exception. As you see i am using exactly the same format as the recorded WAV file (Extension encoding, 44100 etc.), except the bitrate which is lower in the target waveformat.

What would be the correct codeto do the bitrate conversion from a Wav file contained in a MemoryStream? my goal is to get a 320KBPS file.

Upvotes: 0

Views: 4165

Answers (1)

Mark Heath
Mark Heath

Reputation: 49482

For a given sample rate, bit depth, and channel count, PCM audio always has the same bitrate (calculated by multiplying those three values together). If you want to reduce the bitrate, you must change one of those three (lowering the sample rate is probably the best option unless you can go from stereo to mono).

Really you should be thinking of encoding to a format like MP3, WMA or AAC, which will let you select your preferred bitrate.

Upvotes: 1

Related Questions