using NAudio.Wave; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOTContainer.Common { public class BaiduSpeech { private int deviceNumber = 0; // 选择的录音设备下标。多个设备时可设置为用户选择 private WaveIn waveIn; // waveIn操作类 private WaveFormat recordingFormat; // 录音格式 private WaveFileWriter writer; // 录音文件操作类 StringBuilder result = new StringBuilder();//存储最终识别的结果 int totalLength = 0;//用来记录总的识别后的结果的长度,判断是否超过缓存最大值 /// /// 单例模式 /// public static BaiduSpeech baiduSpeech { get { if (_baiduSpeech == null) _baiduSpeech = new BaiduSpeech(); return _baiduSpeech; } } private static BaiduSpeech _baiduSpeech = new BaiduSpeech(); private BaiduSpeech() { } /// /// 录音信息初始化 /// public void InitSpeech() { try { recordingFormat = new WaveFormat(16000, 16, 1); // 设置麦克风操作对象 waveIn = new WaveIn(); waveIn.DeviceNumber = deviceNumber; // 设置使用的录音设备 waveIn.DataAvailable += OnDataAviailable; // 接收到音频数据时,写入文件 waveIn.RecordingStopped += OnRecordingStopped; // 录音结束时执行 waveIn.WaveFormat = recordingFormat; } catch (Exception ex) { Log.MyLog.WriteLogFile("语音初始化失败:"+ ex.ToString(), "BaiduSpeech"); } } /// /// 开始录音 /// /// internal bool StartRecorder(string filename = "speech.wav") { try { totalLength = 0; // 设置文件操作类 writer = new WaveFileWriter(filename, recordingFormat); result.Clear(); // 开始录音 waveIn.StartRecording(); } catch (Exception ex) { //结束录音 StopRecorder(); Log.MyLog.WriteLogFile("录音失败:" + ex.ToString(), "BaiduSpeech"); } return true; } /// /// 结束录音 /// /// internal bool StopRecorder() { waveIn.StopRecording(); return true; } /// /// 录音回调函数,写入数据 /// /// /// private void OnDataAviailable(object sender, WaveInEventArgs e) { try { byte[] buffer = e.Buffer; int bytesRecorded = e.BytesRecorded; long maxFileLength = this.recordingFormat.AverageBytesPerSecond * 60; var toWrite = (int)Math.Min(maxFileLength - writer.Length, bytesRecorded); if (toWrite > 0) { writer.Write(buffer, 0, bytesRecorded); } } catch (Exception ex) { Log.MyLog.WriteLogFile("录音写入失败:" + ex.ToString(), "BaiduSpeech"); } } /// /// 录音结束回调函数 /// /// /// private void OnRecordingStopped(object sender, StoppedEventArgs e) { writer.Dispose(); BaiduSpeechApi(); } /// /// 百度语音识别 /// private string BaiduSpeechApi() { try { var APP_ID = ""; var API_KEY = ""; var SECRET_KEY = ""; var client = new Baidu.Aip.Speech.Asr(APP_ID, API_KEY, SECRET_KEY); client.Timeout = 30000; // 修改超时时间 var data = File.ReadAllBytes("speech.wav"); // 可选参数 var options = new Dictionary { {"dev_pid", 1537} //语音模型1536代表普通话,其他请查看官方文档 }; client.Timeout = 120000; // 若语音较长,建议设置更大的超时时间. ms var result = client.Recognize(data, "pcm", 16000, options); return JsonConvert.SerializeObject(result); } catch (Exception ex) { Log.MyLog.WriteLogFile("百度语音识别失败:" + ex.ToString(), "BaiduSpeech"); return null; } } } }