文字轉語音小軟體
把文字轉成語音這個功能是很常用的,如果不追求語音個性,只需要短短几行程式碼就可以實現。
程式碼,專案中引用
using System.Speech.Synthesis;
四行程式碼實現說話:
using (SpeechSynthesizer voice = new SpeechSynthesizer()) { voice.Rate = 1; voice.Volume = 100; voice.Speak("小y設計"); }
封裝一下:
usingSystem; using System.Collections.Generic; using System.Linq; using System.Speech.Synthesis; using System.Text; using System.Threading.Tasks; namespace SpeakHello { public class SoundHelper { /// <summary> /// 預設音量[0,100] /// </summary> public static int DefaultVolume = 100; /// <summary> /// 預設音速[-10,10] /// </summary> public static int DefaultRate = 1; public static void Speak(string msg) { Speak(msg, DefaultRate, DefaultVolume); } /// <summary> /// 播報語音 /// </summary> ///<param name="msg">內容</param> /// <param name="rate">語速[-10,10]</param> /// <param name="volume">音量[0,100]</param> public static void Speak(string msg, int rate, int volume) { using (SpeechSynthesizer voice = new SpeechSynthesizer()) { voice.Rate = rate; voice.Volume = volume; voice.Speak(msg); } } } }
拓展一下:
除了預設的安娜語音外,還可以安裝其他聲音:Microsoft Mary,Microsoft Mike和Sample TTS Voice
speaker.SelectVoice("Microsoft Mike");
System.Speech和Microsoft.Speech是不同的,並且為了避免混淆,應該只選擇其中之一。
對於System.Speech
- 轉到設定/區域和語言/新增語言
- 從語言設定中,下載語音
例如Helen位於en_US軟體包中。因此,應通過新增英語(美國)語言來下載其他語音。
對於Microsoft.Speech
- 從下面的連結下載語音
- 新增對 專案中的Microsoft.Speech DLL
可以從下面的連結下載Microsoft語音識別和文字到語音引擎資料檔案;
用於Microsoft支援的語言的語音識別和文字到語音引擎https://www.microsoft.com/en-us/download/details.aspx?id=27224
有關更多資訊:
Microsoft語音程式設計指南
https://docs.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh378466(v%3doffice.14)
SpeechSynthesizer.SelectVoice方法
https://docs.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/dd167624(v%3Doffice.14)
System.Speech.Synthesis名稱空間
https://docs.microsoft.com/en-us/dotnet/api/system.speech.synthesis?view=netframework-4.7.2