Tuesday, September 28, 2010

Record Sound from the Microphone

In today's post I want to describe how to record sound from a microphone. In C# we therefor need the WinAPI function mciSendString().
The Media Control Interface (MCI) is an interface, which provides commands to play and record multimedia elements. With the previously described function these commands can be send to the computer and thus be processed there.
The function mciSendString() is contained in the file winmm.dll and can be included as follows (to include external libraries using System.Runtime.InteropServices is needed):

private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

The parameters have the following meaning:
  • lpstrCommand: MCI command to be send
  • lpstrReturnString: if necessary, a buffer saving the result
  • uReturnLength: size of this buffer
  • hwndCallback: window handle, which shall be notified on return

To control the microphone we only need the 1st parameter and handover "" respectively 0 for the others.
To start the recording, we then need the commands "open new Type waveaudio Alias recsound" and "record recsound", to stop it "save recsound" and "close recsound".
The code of a Windows Forms Application having 2 buttons to start and stop the recording could look as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        private static extern int mciSendString(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);

        public Form1()

        // start the recording
        private void button1_Click(object sender, EventArgs e)
            mciSendString("open new Type waveaudio Alias recsound""", 0, 0);
            mciSendString("record recsound""", 0, 0);

        // stop the recording
        private void button2_Click(object sender, EventArgs e)
            mciSendString("save recsound C:\\records\\record1.wav""", 0, 0);
            mciSendString("close recsound""", 0, 0);


No comments:

Post a Comment