1. 引用System.Speech 2. 通過SpeechSynthesizer類朗讀文本 new SpeechSynthesizer().SpeakAsync("我們都是好孩子We're good kids.") 3. Speck vs SpeckAsync函數 PlayAsync--異常播放, ...
1. 引用System.Speech
2. 通過SpeechSynthesizer類朗讀文本
new SpeechSynthesizer().SpeakAsync("我們都是好孩子We're good kids.")
3. Speck vs SpeckAsync函數
- PlayAsync--異常播放,可以將需要朗讀的文本進行排隊。如果不需要,可以按如下取消當前的播放操作。
- Speak--同步播放,會卡UI線程。如果在朗讀時,不影響界面操作,則不應使用此函數
1 private SpeechSynthesizer speechSyn=new SpeechSynthesizer(); 2 /// <summary> 3 /// 非同步播放 4 /// </summary> 5 private void PlayAsync() 6 { 7 var currentSpokenPrompt = speechSyn.GetCurrentlySpokenPrompt(); 8 if (currentSpokenPrompt != null) 9 { 10 speechSyn.SpeakAsyncCancel(currentSpokenPrompt); 11 } 12 speechSyn.SpeakAsync(richTextBox1.Text); 13 } 14 /// <summary> 15 /// 同步播放 16 /// 註:卡UI 17 /// </summary> 18 private void Play() 19 { 20 using (SpeechSynthesizer speechSyn = new SpeechSynthesizer()) 21 { 22 speechSyn.Speak(richTextBox1.Text); 23 } 24 }
4. 設置朗讀角色
1 var speechSynthesizer = new SpeechSynthesizer(); 2 var voices= speechSynthesizer.GetInstalledVoices(CultureInfo.CurrentCulture).Select(x => x.VoiceInfo.Name).ToList(); 3 speechSynthesizer.SelectVoice(voices[0]); 4 speechSynthesizer.SpeakAsync("我們都是好孩子We're good kids.");
5. 其它
- Rate -- 語速設置,預設為0
- Volume -- 音量設置
6. 導出音頻文件
可以將文本語音合成後,導出成一個wav、mp3等音頻文件。
1 private void ExportAudioFile() 2 { 3 using (SpeechSynthesizer speechSyn = new SpeechSynthesizer()) 4 { 5 speechSyn.Volume = 50; 6 speechSyn.Rate = 0; 7 8 var filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\{richTextBox1.Text}.mp3"; 9 if (File.Exists(filePath)) 10 { 11 File.Delete(filePath); 12 } 13 14 speechSyn.SetOutputToWaveFile(filePath); 15 speechSyn.Speak(richTextBox1.Text); 16 speechSyn.SetOutputToDefaultAudioDevice(); 17 18 MessageBox.Show($"保存錄音文件成功,保存路徑:{filePath}"); 19 } 20 }
Demo下載