本文采用简单的方式,如需使用其他功能,请访问Naudio相关功能
1.using NAudio.Wave;从麦克风输入到声卡输出,并操作数据
//创建输出对象WaveOut waveOut = new WaveOut();//创建输入对象WaveIn waveIn = new WaveIn();//创建缓冲区BufferedWaveProvider bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(16000, 16, 1));public void PlaySound() {//输入音频参数设置 16k/16位/通道1waveIn.WaveFormat = new WaveFormat(16000, 16, 1);//为wavein的回调函数添加事件,用于操作数据waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);//播放waveOut.Init(bufferedWaveProvider);waveOut.Play();}/// <summary>/// 回调函数/// </summary>/// <param name=\"sender\"></param>/// <param name=\"e\"></param>private void waveIn_DataAvailable(object sender, WaveInEventArgs e){//e.Buffer为用于操作的数组,类型为bytebufferedWaveProvider.AddSamples(e.Buffer,0,e.BytesRecorded);byte[] WaveIn_Data = e.Buffer;}
2.利用Naudio录音,如对wav文件的头不了解请访问wav头文件格式
//新建文件操作对象,System.Windows.Forms.Application.StartupPath为程序bin目录 wave为文件夹名称 格式为wavWaveFileWriter waveFileWriter = new WaveFileWriter(System.Windows.Forms.Application.StartupPath + \"\\\\wave\\\\.wav\", new WaveFormat(16000, 16, 1));private void waveIn_DataAvailable(object sender, WaveInEventArgs e){//e.Buffer为用于操作的数组,类型为bytebufferedWaveProvider.AddSamples(e.Buffer, 0, e.BytesRecorded);byte[] WaveIn_Data = e.Buffer;waveFileWriter.Write(WaveIn_Data, 0, WaveIn_Data.Length);}//先写入头文件,如对wav文件的头不了解请访问public void CreateWav() {byte[] bxt = new byte[44] { 82, 73, 70, 70, 36, 124, 7, 0, 87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 1, 0, 64, 31, 0, 0, 128, 62, 0, 0, 2, 0, 16, 0, 100, 97, 116, 97, 0, 124, 7, 0 };waveFileWriter.Write(bxt, 0, bxt.Length);}//停止录音private void stopMsg_Click(object sender, EventArgs e){waveFileWriter.Close();}
3.播放文件
//播放private void PlayWav_Click(object sender, EventArgs e){//文件打开对象OpenFileDialog dialog = new OpenFileDialog();//设置格式dialog.Filter = \"Wave File (*.wav)|*.wav;\";//默认路径dialog.InitialDirectory = System.Windows.Forms.Application.StartupPath + \"\\\\wave\\\\\";//是否选取文件if (dialog.ShowDialog() == DialogResult.OK){//文件访问对象AudioFileReader waveReader = new AudioFileReader(dialog.FileName);WaveOut waveOutPlay=new WaveOut();waveOutPlay.Init(waveReader);// 设置音量 0~1waveOutPlay.Volume = 1f;waveOutPlay.Play();}}
如需要获取播放状态,我认为可以新建线程或定时器监听状态
if (waveOutPlay.PlaybackState != PlaybackState.Playing) { }
如有什么错误的地方,望各位提出改进意见,让博主能够更快提升自己,谢谢