c#录音和放音,超简单!不用DirectX
最近在做android与C#录音并互相通信的小东西。但是卡在C#录音这儿了。找了好久,说的都是DirectX,可是我总是安装不上,这才找到了这个简单的录音方法。当然,如果你想要录得好并且处理音频,那还是用用DirectX吧!原文:http://www.cnblogs.com/zrx401558287/archive/2008/11/28/1343160.html
using System.Runtime.InteropServices; [DllImport("winmm.dll", EntryPoint = "mciSendString", CharSet = CharSet.Auto)] public static extern int mciSendString( string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback ); private void button1_Click(object sender, EventArgs e) { mciSendString("set wave bitpersample 8", "", 0, 0); mciSendString("set wave samplespersec 20000", "", 0, 0); mciSendString("set wave channels 2", "", 0, 0); mciSendString("set wave format tag pcm", "", 0, 0); mciSendString("open new type WAVEAudio alias movie", "", 0, 0); mciSendString("record movie", "", 0, 0); } private void button2_Click(object sender, EventArgs e) { mciSendString("stop movie", "", 0, 0); mciSendString("save movie 1.wav", "", 0, 0); mciSendString("close movie", "", 0, 0); }
button1是开始录音,button2是结束录音。你当然也可以通过逻辑判断来只使用一个button。
录音文件保存到了该项目下bin/Debug目录下了。文件名是1.wav。所以你可以在这里改成你自己的文件名
mciSendString("save movie "+yourfilename, "", 0, 0);
很简单吧?
下面是放音。
放音我使用的是WindowsMediaPlayer这个组件:
我将它设为不可见,自己用按键控制它的播放与暂停。
private void button1_Click(object sender, EventArgs e) { if(!playing) { playing = true; button1.Text = "停止"; this.axWindowsMediaPlayer1.URL ="your voice file name"; axWindowsMediaPlayer1.Ctlcontrols.play(); } else { axWindowsMediaPlayer1.Ctlcontrols.stop(); playing=false; button1.Text="播放"; } }
也就是通过URL属性设置播放的文件。
那如果它自己播放结束了怎么办呢?
当然就需要事件啦!
private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e) { if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsStopped) { if (playing) { playing = false; button1.Text = "播放"; } if (playing_my) { playing_my = false; btn_playmy.Text = "播放我的"; } } }
这两个强大的工具让我们完成了简单的开发!