Recording and Playing Audio in C#

One of the shortcomings of .NET is the lack of classes and methods for processing audio files and streams. The quickest way to add this functionality is through the MCI commands in the Windows API as defined in the winmm.dll library. The single function mciSendString can execute all of the necessary commands to record and play sound files. Wrapping this functionality in a class provides a simple interface to recording and playing audio files.

Because the mciSendString method of the winmm.dll is not exposed through a .NET interface, the InteropServices makes this API function available through a DllImport attribute.

using System.Runtime.InteropServices;

public class MCIAudio
{
   [DllImport("winmm.dll")]
   private static extern long mciSendString(string strCommand, StringBuilder strReturn, int iReturnLength, IntPtr oCallback);

   public static void OpenNew()
   {
      mciSendString("open new type waveaudio alias recsound", null, 0, IntPtr.Zero);
   }

   public static void OpenFile(string fileName)
   {
      mciSendString(string.Format("open \"{0}\" type waveaudio alias recsound", fileName), null, 0, IntPtr.Zero);
   }

   public static void Record()
   {
      mciSendString("record recsound", null, 0, IntPtr.Zero);
   }

   public static void Play()
   {
      mciSendString("play recsound", null, 0, IntPtr.Zero);
   }

   public static void SaveRecording(string fileName)
   {
      mciSendString(string.Format("save recsound \"{0}\"", fileName), null, 0, IntPtr.Zero);
   }

   public static void Pause()
   {
      mciSendString("pause recsound", null, 0, IntPtr.Zero);
   }

   public static void Stop()
   {
      mciSendString("close recsound", null, 0, IntPtr.Zero);
   }
}

This class can easily be modified to support other features available through MCI commands.