This project has moved. For the latest updates, please go here.

Invert audio waves

Jun 10, 2010 at 11:47 AM
Has anyone tested how to invert audio waves in code? I'm doing some tests with noise cancellation, and as of now I'm mainly just searching for code to do the inversion of the audio.
Coordinator
Jun 11, 2010 at 9:51 AM

you invert audio waves by just multiplying every sample by -1

it will only succeed in cancelling noise if the inverted signal is perfectly in sync with the original. otherwise you will just make an echo.

Sep 27, 2013 at 6:53 PM
Can you give a code example? This is what I've tried:
public static void InvertWaveFile(string inputFile, string outputFile)
        {
            using (WaveFileReader reader = new WaveFileReader(inputFile))
            {
                int blockAlign = reader.WaveFormat.BlockAlign;
                using (WaveFileWriter writer = new WaveFileWriter(outputFile, reader.WaveFormat))
                {
                    sbyte[] buffer = new sbyte[blockAlign];
                    long samples = reader.Length / blockAlign;
                    for (long sample = 0; sample <= reader.Length; sample++)
                    {
                        reader.Position = sample * blockAlign;
                        reader.Read(buffer, 0, blockAlign);
                        int byteCount = 0;
                        for (byteCount = 0; byteCount <= buffer.Length; byteCount++)
                        {
                            buffer[byteCount] = Convert.ToSByte(Convert.ToDouble(buffer[byteCount]) * -1);
                        }
                        
                        writer.WriteData(buffer, 0, blockAlign);
                    }
                }
            }
        }
The code above doesn't work because this requires Signed double rather then a double. NAudio seems to expect a double though... What am I doing wrong??

Many Thanks,
Coordinator
Sep 27, 2013 at 7:41 PM
it depends what bit depth your WAV file is at. I'm guessing it is 16 bit, so use BitConverter.ToInt16 on every pair of bytes, then multiply the resulting short by -1, before using BitConverter.GetBytes on it again.