C# 文本转语音朗读
1. 利用DONET框架自带的 SpeechSynthesizer ,缺点是没有感情色彩,抑扬顿挫等。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Speech.Synthesis; using System.Threading; using Microsoft.Win32; namespace MSSpeech { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); speech = new SpeechSynthesizer(); speech.Rate = rate; // speech.SelectVoice("Microsoft Lili");//设置播音员(中文) speech.SelectVoice("Microsoft Anna"); //英文 speech.Volume = value; speech.SpeakCompleted += speech_SpeakCompleted;//绑定事件 Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing); } void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) { speech.SpeakAsyncCancelAll();//停止阅读 speech.SpeakCompleted -= speech_SpeakCompleted; } private SpeechSynthesizer speech; /// <summary> /// 音量 /// </summary> private int value = 100; /// <summary> /// 语速 /// </summary> private int rate; private string words = ""; private void btnSpeech_Click(object sender, RoutedEventArgs e) { test(); } void test() { string text = textBox1.Text; if (text.Trim().Length == 0) { MessageBox.Show("不能阅读空内容!", "错误提示"); return; } words = textBox1.Text; new Thread(Speak).Start(); } private void Speak() { speech.SpeakAsync(words);//语音阅读方法 } /// <summary> /// 语音阅读完成触发此事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void speech_SpeakCompleted(object sender, SpeakCompletedEventArgs e) { btnSpeech.Content = "语音试听"; } // <summary> /// 生成语音文件的方法 /// </summary> /// <param name="text"></param> private void SaveFile(string text) { speech = new SpeechSynthesizer(); var dialog = new SaveFileDialog(); dialog.Filter = "*.wav|*.wav|*.mp3|*.mp3"; dialog.ShowDialog(); string path = dialog.FileName; if (path.Trim().Length == 0) { return; } speech.SetOutputToWaveFile(path); speech.Volume = value; speech.Rate = rate; speech.Speak(text); speech.SetOutputToNull(); MessageBox.Show("生成成功!在" + path + "路径中!", "提示"); } } }
2. 百度语音合成,在线模式,缺点需要联网发送请求,如果文本太多就会有延迟问题需要解决。
请求API例子:
Request URL:http://ai.baidu.com/aidemo
Request Method:POST
Status Code:200 OK
Remote Address:220.181.164.109:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Access-Control-Allow-Origin:*
Connection:keep-alive
Content-Type:text/json; charset=UTF-8
Date:Wed, 26 Sep 2018 07:41:51 GMT
Server:Apache
Tracecode:25108570390947468554092615
Tracecode:25108562210900343306092615
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:751
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:BAIDUID=2BF1001DCF35B79BEFB7C9C63C0C90B7:FG=1; BIDUPSID=2BF1001DCF35B79BEFB7C9C63C0C90B7; PSTM=1517209070; H_PS_PSSID=26523_1431_21080_26350_20928; Hm_lvt_8b973192450250dd85b9011320b455ba=1537947694; Hm_lpvt_8b973192450250dd85b9011320b455ba=1537947694; seccode=45956e63379931ef6aa0f3c472ad195c
Host:ai.baidu.com
Origin:http://ai.baidu.com
Referer:http://ai.baidu.com/tech/speech/tts
User-Agent:Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
type:tns
spd:5
vol:5
per:4
tex:百度语音,面向广大开发者永久免费开放语音合成技术。所采用的离在线融合技术,根据当前网络状况,自动判断使用本地引擎或云端引擎,进行语音合成,再也不用担心流量消耗了
3. 用 DotNetSpeech.dll 第三方组件,缺点 朗读比较生硬,语音库和本地系统相关。
代码:
SpVoice sp = new SpVoice();
sp.Rate = GetSpeedSelected();
SpeechVoiceSpeakFlags sFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
sp.Speak(text, sFlags);
后记:
下面是测试百度文本转语音的例子:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; using System.Windows; using System.Windows.Threading; using System.Windows.Controls; namespace TextSpeech { public class BaiduSpeech { public static string Text2Voice(string sText) { sText = Uri.EscapeDataString(sText ); string post = "type=tns&spd=5&pit=10&vol=5&per=4&tex=%E6%8F%90%E4%BE%9B%E5%A4%9A%E7%A7%8D%E5%8F%91%E9%9F%B3%E4%BA%BA%0A%E6%8F%90%E4%BE%9B%E5%9F%BA%E7%A1%80%E9%9F%B3%E5%BA%93%E5%92%8C%E7%B2%BE%E5%93%81%E9%9F%B3%E5%BA%93%E5%85%B19%E7%A7%8D%E5%8F%91%E9%9F%B3%E4%BA%BA%E4%BE%9B%E6%82%A8%E9%80%89%E6%8B%A9%EF%BC%8C%E9%80%82%E7%94%A8%E4%BA%8E%E6%B3%9B%E9%98%85%E8%AF%BB%E3%80%81%E8%AE%A2%E5%8D%95%E6%92%AD%E6%8A%A5%E3%80%81%E6%99%BA%E8%83%BD%E7%A1%AC%E4%BB%B6%E7%AD%89%E5%BA%94%E7%94%A8%E5%9C%BA%E6%99%AF%EF%BC%8C%E5%8D%B3%E5%B0%86%E6%8E%A8%E5%87%BA%E6%9B%B4%E5%A4%9A%E7%89%B9%E8%89%B2%E5%8F%91%E9%9F%B3%E4%BA%BA"; post = "type=tns&spd=5&pit=10&vol=5&per=4&tex="+sText; string s= HttpHelper2.httpPost("http://ai.baidu.com/aidemo", post ); // MessageBox.Show(s); //if get OK result: {"errno":0,"msg":"success","data":"data:audio/x-mpeg;base64,//MoxAA............VVVV"} //convert from audio base64 string to byte if (s.Contains("data:audio\/x-mpeg;base64"))//success get audio { s = System.Text.RegularExpressions.Regex.Unescape(s); string stringInBase64 = s.Replace("{"errno":0,"msg":"success","data":"data:audio/x-mpeg;base64,","").Replace(""}",""); byte[] bytes = System.Convert.FromBase64String(stringInBase64); WriteByteToFile(bytes, "temp.mp3"); //保存本地文件后可用 MediaElement 组件来播放。 // playAudio(bytes);//播放声音,如果不是WAV格式的流会失败。 // PlaySound(md,AppDomain.CurrentDomain.BaseDirectory + "\temp.mp3"); } return s; } /// <summary> /// 写byte[]到fileName /// </summary> /// <param name="pReadByte">byte[]</param> /// <param name="fileName">保存至硬盘路径</param> /// <returns></returns> static bool WriteByteToFile(byte[] pReadByte, string fileName) { FileStream pFileStream = null; try { pFileStream = new FileStream(fileName, FileMode.OpenOrCreate); pFileStream.Write(pReadByte, 0, pReadByte.Length); } catch { return false; } finally { if (pFileStream != null) pFileStream.Close(); } return true; } static void playAudio(byte[] data) { MemoryStream ms = new MemoryStream(data); ms.Position = 0; System.Media.SoundPlayer player = new System.Media.SoundPlayer(); player.Stream = ms; player.LoadAsync(); player.Play();//The wave header is corrupt. 说明这个不是WAV格式文件流 } static void PlaySound(MediaElement md ,string url) { md.LoadedBehavior = MediaState.Manual; md.IsEnabled = true; md.Stop(); md.Source = null; md.Source = new Uri(url); md.Play(); } } public class HttpHelper2 { CookieContainer myCookieContainer = new CookieContainer(); public static string httpPost(string url, string post) { string s = ""; try { byte[] data = Encoding.ASCII.GetBytes(post); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = "POST"; req.Headers.Add("Cookie", "BAIDUID=CA97D41AACE2AD8A2750225E9F53C9BA:FG=1; BIDUPSID=CA97D41AACE2AD8A2750225E9F53C9BA; PSTM=1562830960; BDUSS=1Vib0ZXRjlqYnBmNG1SaW4wZjJ0SE0wRW40MXhJdE1JT01RQmk5QmtoMzB2VmRkSVFBQUFBJCQAAAAAAAAAAAEAAADSJwUAd2dzY2QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPQwMF30MDBdN; H_WISE_SIDS=126894_127760_132206_132550_133721_120202_133016_132911_133041_131246_132439_130762_132378_131518_118889_118863_118845_118826_118787_107320_133159_132780_134393_133352_129647_134434_124636_128968_132540_133837_133473_131906_133838_133847_132552_134460_133424_134319_134214_129645_131423_134345_133587_110085_134152_127969_131299_127318_127417_134150_133668_134352; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; H_PS_PSSID=29716_1446_21115_29523_29520_29721_29568_29220; PSINO=6; Hm_lvt_8b973192450250dd85b9011320b455ba=1567135060; Hm_lpvt_8b973192450250dd85b9011320b455ba=1567135060"); req.ContentType = "application/x-www-form-urlencoded"; req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36"; req.Referer = "http://ai.baidu.com/tech/speech/tts?track=cp:ainsem|pf:pc|pp:chanpin-yuyin|pu:yuyin-yuyinhecheng-pinpai|ci:|kw:10003541"; req.ContentLength = data.Length; req.GetRequestStream().Write(data, 0, data.Length); // req.CookieContainer = myCookieContainer; HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); // myCookieContainer.Add(resp.Cookies); StreamReader r = new StreamReader(resp.GetResponseStream()); s = r.ReadToEnd(); r.Close(); resp.Close(); req.Abort(); } catch (Exception ex) { s = ex.Message; } return s; } } }