Record Voice and Play Recorded Sound (C#)


DOWNLOAD


Today in C#, i will teach you how to create a program that records voice and plays it (microphone) using C#.
Now, let's start this tutorial!
1. Let's start with creating a Windows Form Application for this tutorial by following the following steps in Microsoft Visual Studio: Go to File, click New Project, and choose Windows Application and name your program as microphone.
2. Next, add three buttons named Button1 as record button for recording voice, Button2 as save and stop button, and Button3 for playing the recorded audio. You must design your interface like this:
design
3, Import System.Runtime.InteropServices namespace.
  1. using System.Diagnostics;
  2. using System;
  3. using System.Windows.Forms;
  4. using System.Collections;
  5. using System.Drawing;
  6. using System.Data;
  7. using System.Collections.Generic;
  8.  
  9.  
  10. using System.Runtime.InteropServices;
4. Now, in your code module, create a function named record that will access the winmm.dll.
  1. [DllImport("winmm.dll",EntryPoint="mciSendStringA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
  2.  
  3. private static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
5.For record button for Button1, put this code below.
  1. public void Button1_Click(System.Object sender, System.EventArgs e)
  2. {
  3. record("open new Type waveaudio Alias recsound", "", 0, 0);
  4.  
  5. record("record recsound", "", 0, 0);
  6. }
The function named record was called here to open a wav audio file that is named as recsound. Then this will record sound as you click the record button. Note: Provide headset with microphone or speaker in your PC or laptop for you to say the words to record.
6. For save and stop button for Button2, put this code below.
  1. public void Button2_Click(System.Object sender, System.EventArgs e)
  2. {
  3. record("save recsound c:\\mic.wav", "", 0, 0);
  4.  
  5. record("close recsound", "", 0, 0);
  6. }
The recsound alias that we initialized in the record button was called here. This button will save the recorded audio file and saved into C directory and will named as mic.wav. Then after saving, we close the recorded sound.
7.For play button for Button3, put this code below.
  1. public void Button3_Click(System.Object sender, System.EventArgs e)
  2. {
  3. (new Microsoft.VisualBasic.Devices.Audio()).Play("c:\\mic.wav");
  4. }
We used the Play function in Audio to play the saved file in C Directory, the mic.wav, that we recorded its sound earlier.
Click first record, say the words you wanted to say, click the save button, and play it. :)

SHARE THIS
Previous Post
Next Post