C# 語音合成


微軟MS的文本轉語音

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下載

 

第三方的語音合成接口

如果是英文朗讀的話,有道的效果最好。可以下載Demo體驗下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM