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 //**************************************结束****************************************************//