Search code examples
c#audio-recordingmci

Correct way to set MCI audio parameters in C#


I'm trying to record wav files. My app needs to allow the user to choose between different sample rates and bit depths. No matter what syntax I try though, I always get files with the same bit rate. Can someone please tell me what I'm doing wrong?

[DllImport("winmm.dll")]
private static extern long mciSendString(string command, StringBuilder retstring, int returnLength, IntPtr callback);

...

private void btnRecord_Click(object sender, EventArgs e)
{
    mciSendString("Open new Type waveaudio alias recSound", null, 0, IntPtr.Zero);
    mciSendString("setaudio recSound algorithm pcm", null, 0, IntPtr.Zero);
    mciSendString("setaudio recSound samplespersec to 44100", null, 0, IntPtr.Zero);
    DisableRecordingButtons();
    mciSendString("Record recSound", null, 0, IntPtr.Zero);
}

Solution

  • The setaudio command is used for video not audio. Apparently you need to set the audio parameters with the set command, and the parameters need to be set in the correct order. The set command should look like this...

    string setCommand = "set recSound alignment 4 bitspersample " + BitDepth.ToString() + " samplespersec " + SampleRate.ToString() + " channels 1 bytespersec " +
                (BitDepth * SampleRate * 1 / 8).ToString() + " time format milliseconds format tag pcm";
            mciSendString(setCommand, null, 0, IntPtr.Zero);
    

    The alignment argument is always 4, and the bytespersec is always (bitspersample * samplespersec * channels / 8).