[How-to] Record sound in .NET application

By | March 5, 2015

Advertisement from Google

First import mciSendStringA from winmm.dll:

[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

To start recording:

Advertisement from Google

mciSendString("open new Type waveaudio Alias recsound", null, 0, 0);
mciSendString("set recsound time format ms bitspersample 16 channels 2 samplespersec 48000 bytespersec 192000 alignment 4", null, 0, 0);
mciSendString("record recsound", null, 0, 0);

To stop recording and save the result to file:

var filePath = "C:\\test\\result.wav";
mciSendString("save recsound " + filePath, null, 0, 0);
mciSendString("close recsound ", null, 0, 0);

Note: To save a file output folder (in our example C:\test) must be created before calling “save recsound” command.

Leave a Reply

Your email address will not be published. Required fields are marked *