Martin Delille
Martin Delille

Reputation: 11780

Read a sound backward with DirectSound

Is it possible to read a sound backward with the managed version of DirectSound? If not is there another library allowing to make it easily?

Upvotes: 2

Views: 1775

Answers (1)

Mark Heath
Mark Heath

Reputation: 49482

You can use the WaveFileReader and WaveFileWriter classes from NAudio to reverse a WAV file. You need to make sure you use the BlockAlign property of the WaveFormat to read all the bytes for a single sample (4 for stereo 16 bit audio).

    public static void ReverseWaveFile(string inputFile, string outputFile)
    {
        using (WaveFileReader reader = new WaveFileReader(inputFile))
        {
            int blockAlign = reader.WaveFormat.BlockAlign;
            using (WaveFileWriter writer = new WaveFileWriter(outputFile, reader.WaveFormat))
            {
                byte[] buffer = new byte[blockAlign];
                long samples = reader.Length / blockAlign;
                for (long sample = samples - 1; sample >= 0; sample--)
                {
                    reader.Position = sample * blockAlign;
                    reader.Read(buffer, 0, blockAlign);
                    writer.WriteData(buffer, 0, blockAlign);
                }
            }
        }
    }

Upvotes: 7

Related Questions