C#實(shí)現(xiàn)電腦麥克風(fēng)錄音
本實(shí)例通過(guò)Naudio庫(kù)完成麥克風(fēng)錄音并把PCM脈沖信號(hào)保存成wav音頻文件。關(guān)于音頻的采樣率、比特率、聲道等問(wèn)題請(qǐng)查閱相關(guān)資料,本示例不做解釋。Naudio庫(kù) 請(qǐng)從NuGet搜索并下載。
錄音接口類(lèi):
public interface ISpeechRecorder { void SetFileName(string fileName); void StartRec(); void StopRec(); }
錄音實(shí)現(xiàn)類(lèi):
using System; using NAudio.Wave; namespace Test { class NAudioRecorder : ISpeechRecorder { public WaveIn waveSource = null; public WaveFileWriter waveFile = null; private string fileName = string.Empty; /// <summary> /// 第二步:開(kāi)始錄音 /// </summary> public void StartRec() { try { waveSource = new WaveIn();//保證電腦有麥克接入否則報(bào)錯(cuò)。 waveSource.WaveFormat = new WaveFormat(16000, 16, 1); // 16KHz,16bit,單聲道的錄音格式 waveSource.DataAvailable += new EventHandler<WaveInEventArgs>(waveSource_DataAvailable); waveSource.RecordingStopped += new EventHandler<StoppedEventArgs>(waveSource_RecordingStopped); waveFile = new WaveFileWriter(fileName, waveSource.WaveFormat); waveSource.StartRecording(); } catch(Exception e) { throw new Exception(e.Message); } } /// <summary> /// 第三步:停止錄音 /// </summary> public void StopRec() { waveSource.StopRecording(); // Close Wave(Not needed under synchronous situation) if (waveSource != null) { waveSource.Dispose(); waveSource = null; } if (waveFile != null) { waveFile.Dispose(); waveFile = null; } } /// <summary> /// 第一步:設(shè)置錄音結(jié)束后保存的文件路徑 /// </summary> /// <param name="fileName">保存wav文件的路徑名</param> public void SetFileName(string fileName) { this.fileName = fileName; } /// <summary> /// 開(kāi)始錄音回調(diào)函數(shù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void waveSource_DataAvailable(object sender, WaveInEventArgs e) { if (waveFile != null) { waveFile.Write(e.Buffer, 0, e.BytesRecorded); waveFile.Flush(); } } /// <summary> /// 錄音結(jié)束回調(diào)函數(shù) /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void waveSource_RecordingStopped(object sender, StoppedEventArgs e) { if (waveSource != null) { waveSource.Dispose(); waveSource = null; } if (waveFile != null) { waveFile.Dispose(); waveFile = null; } } } }
調(diào)用方法:
NAudioRecorder nar=new NAudioRecorder(); nar.SetFileName(@"d:\naudio.wav"); nar.StartRec(); nar.StopRec();
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
如何用C#在PC上查找連接藍(lán)牙設(shè)備并實(shí)現(xiàn)數(shù)據(jù)傳輸
這篇文章主要介紹了如何用C#在PC上查找連接藍(lán)牙設(shè)備并實(shí)現(xiàn)數(shù)據(jù)傳輸,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03c#封裝百度web服務(wù)geocoding api 、百度坐標(biāo)轉(zhuǎn)換示例
這篇文章主要介紹了c#封裝百度Web服務(wù)geocoding api 、百度坐標(biāo)轉(zhuǎn)換,需要的朋友可以參考下2014-04-04C#通過(guò)子窗體刷新父窗體的實(shí)現(xiàn)方法
在一些軟件,比如,進(jìn)銷(xiāo)存管理系統(tǒng)中添加銷(xiāo)售單信息時(shí),每個(gè)銷(xiāo)售單都可能對(duì)應(yīng)多種商品,而且在向銷(xiāo)售單中添加商品時(shí),一般都是在新彈出的窗體中選擇商品,這時(shí)就涉及通過(guò)子窗體刷新父窗體的問(wèn)題,本文給大家介紹了C#通過(guò)子窗體刷新父窗體的實(shí)現(xiàn)方法,需要的朋友可以參考下2024-04-04