Today I am going to show you how to create a program that records voice and plays it (microphone) using C#.
- 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 or whatever you want.
- 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.
When design is finished move on to code
Import System.Runtime.InteropServices namespace
- using System.Diagnostics;
- using System;
- using System.Windows.Forms;
- using System.Collections;
- using System.Drawing;
- using Microsoft.VisualBasic;
- using System.Data;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- [DllImport("winmm.dll",EntryPoint="mciSendStringA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
- private static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
- public void Button1_Click(System.Object sender, System.EventArgs e)
- {
- timer1.Enabled = true;
- timer1.Start();
- record("open new Type waveaudio Alias recsound", "", 0, 0);
- record("record recsound", "", 0, 0);
- }
For save and stop button for Button2, put this code below
- public void Button2_Click(System.Object sender, System.EventArgs e)
- {
- timer1.Stop();
- timer1.Enabled = false;
- record("save recsound d:\\mic.wav", "", 0, 0);
- record("close recsound", "", 0, 0);
- }
For play button for Button3, put this code below
- public void Button3_Click(System.Object sender, System.EventArgs e)
- {
- ms = 0;
- h = 0;
- s = 0;
- m = 0;
- timer1.Enabled = false;
- lblhur.Text = "00";
- lblmin.Text = "00";
- lblsecond.Text = "00";
- (new Microsoft.VisualBasic.Devices.Audio()).Play("d:\\mic.wav");
- }
No comments:
Post a Comment