C# 使用System.Speech 進行語音播報和識別ide
1 using System.Speech.Synthesis; 2 using System.Speech.Recognition; 3
4
5 //語音識別
6 SpeechRecognitionEngine recEngine = new SpeechRecognitionEngine(); 7 SpeechSynthesizer speech = new SpeechSynthesizer(); 8
9
10 //**************************使用System.Speech 製做文字轉換成聲音的程序******************************* 11 //rate: 範圍爲:-10~10; 12 //volume: 範圍爲:0~100; 13 //speektext: 待轉換聲音的文字
14 public void SpeechVideo_Read(int rate, int volume, string speektext) //讀
15 { 16 speech.Rate = rate; 17 speech.Volume = volume; 18 speech.SpeakAsync(speektext); 19 } 20
21 public void SpeechVideo_Record(int rate, int volume, string recordtext) //錄音
22 { 23 SpeechSynthesizer speech = new SpeechSynthesizer(); 24 speech.Rate = rate; 25 speech.Volume = volume; 26 SaveFileDialog sfd = new SaveFileDialog(); 27 sfd.Filter = "文本文件(*.wav)|*.wav|全部文件(*.*)|*.*"; 28 //設置默認文件類型顯示順序
29 sfd.FilterIndex = 1; 30 //保存對話框是否記憶上次打開的目錄
31 sfd.RestoreDirectory = true; 32 if (sfd.ShowDialog() == DialogResult.OK) 33 { 34 string localfilepath = sfd.FileName.ToString(); 35 speech.SetOutputToWaveFile(localfilepath); 36 speech.Speak(recordtext); 37 speech.SetOutputToDefaultAudioDevice(); 38 MessageBox.Show("完成錄音!", "提示"); 39 } 40 } 41
42 public void SpeechVideo_Pause() //暫停
43 { 44 speech.Pause(); 45 } 46
47 public void SpeechVideo_Contine() //暫停後繼續
48 { 49 speech.Resume(); 50 } 51 //**************************************結束******************************************************** 52
53
54
55
56 //*****************************************使用System.Speech 製做語音識別程序*********************** 57 //rate: 範圍爲:-10~10; 58 //volume: 範圍爲:0~100; 59 //speektext: 待轉換聲音的文字
60 public void recEngine_Speech_RecordCheck() //讀
61 { 62 Choices preCmd = new Choices(); 63 preCmd.Add(new string[] { "name", "age" }); 64 GrammarBuilder gb = new GrammarBuilder(); 65 gb.Append(preCmd); 66 Grammar gr = new Grammar(gb); 67 recEngine.LoadGrammarAsync(gr); 68 recEngine.SetInputToDefaultAudioDevice(); 69 recEngine.RecognizeAsync(RecognizeMode.Multiple); 70 recEngine.SpeechRecognized += recEngine_SpeechRecognized; 71 } 72
73 public void recEngine_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) 74 { 75 switch (e.Result.Text) 76 { 77 case "name": 78 MessageBox.Show("wangjin"); 79 break; 80 case "age": 81 MessageBox.Show("23"); 82 break; 83 } 84 } 85
86 //**************************************結束****************************************************//