halve the speed of a wav in csharp

To halve the speed of a WAV file in C#, you can use the NAudio library. Here's an example code snippet:

main.cs
using NAudio.Wave;

// Load the WAV file
var reader = new WaveFileReader("input.wav");

// Create a new WAV file to write to
var writer = new WaveFileWriter("output.wav", reader.WaveFormat);

// Change the speed of the input WAV file
var soundTouch = new SoundTouch(reader.WaveFormat.SampleRate, 
                                 reader.WaveFormat.Channels);
soundTouch.Tempo = 0.5f;

// Loop through each block of samples and write them to the output WAV file
var buffer = new float[reader.WaveFormat.SampleRate * reader.WaveFormat.Channels];
int bytesRead;
do
{
    bytesRead = reader.ReadSamples(buffer, 0, buffer.Length);
    soundTouch.PutSamples(buffer, bytesRead / reader.WaveFormat.Channels);
    int samplesAvailable;
    do
    {
        samplesAvailable = soundTouch.ReceiveSamples(buffer, 0, buffer.Length);
        writer.WriteSamples(buffer, 0, samplesAvailable * reader.WaveFormat.Channels);
    } while (samplesAvailable > 0);
} while (bytesRead > 0);

// Clean up
reader.Close();
writer.Close();
1013 chars
32 lines

This code uses the SoundTouch class from the NAudio library to change the tempo of the input WAV file to 0.5, which halves the speed. The loop reads blocks of samples from the input WAV file and writes them to the output WAV file, after passing them through the SoundTouch object. Finally, the input and output WAV files are closed.

gistlibby LogSnag