Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

c# - change wav file ( to 16KHz and 8bit ) with using NAudio

I want to change a WAV file to 8KHz and 8bit using NAudio.

            WaveFormat format1 = new WaveFormat(8000, 8, 1);
            byte[] waveByte = HelperClass.ReadFully(File.OpenRead(wavFile));
            Wave
            using (WaveFileWriter writer = new WaveFileWriter(outputFile, format1))
            {
                writer.WriteData(waveByte, 0, waveByte.Length);
            }

but when I play the output file, the sound is only sizzle. Is my code is correct or what is wrong?

If I set WaveFormat to WaveFormat(44100, 16, 1), it works fine.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A few pointers:

  • You need to use a WaveFormatConversionStream to actually convert from one sample rate / bit depth to another - you are just putting the original audio into the new file with the wrong wave format.
  • You may also need to convert in two steps - first changing the sample rate, then changing the bit depth / channel count. This is because the underlying ACM codecs can't always do the conversion you want in a single step.
  • You should use WaveFileReader to read your input file - you only want the actual audio data part of the file to get converted, but you are currently copying everything including the RIFF chunks as though they were audio data into the new file.
  • 8 bit PCM audio usually sounds horrible. Use 16 bit, or if you must have 8 bit, use G.711 u-law or a-law
  • Downsampling audio can result in aliasing. To do it well you need to implement a low-pass filter first. This unfortunately isn't easy, but there are sites that help you generate the coefficients for a Chebyshev low pass filter for the specific downsampling you are doing.

Here's some example code showing how to convert from one format to another. Remember that you might need to do the conversion in multiple steps depending on the format of your input file:

using (var reader = new WaveFileReader("input.wav"))
{
    var newFormat = new WaveFormat(8000, 16, 1); 
    using (var conversionStream = new WaveFormatConversionStream(newFormat, reader))
    {
        WaveFileWriter.CreateWaveFile("output.wav", conversionStream);
    } 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...