c# 百度语音合成

前段时间作了语音转文字的功能,索性就把文字转语音一块儿作了,参考了下这位朋友的帖子。这里把获得的语音文件直接保存了,mp3格式,须要wav须要转换,百度返回的直接是压缩后的mp3。原文在这:http://blog.csdn.net/u012395622/article/details/46909653#comments,参考api

开始代码:app

首先是stringtoaudio类测试

这里使用的是个人百度语音识别appkey,能够本身去申请,很简单,请参考以前关于语音转文字的帖子或者上面的传送门ui

<pre name="code" class="csharp"><pre name="code" class="csharp"><pre name="code" class="csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;
namespace test
{
 
public class StringToAudio { 
 
string token = "5561738"; string apiKey = "xUdNQCG3rHosEtTH7Ffiw4fI"; string secretKey = "EtHymbgx054QDsAAtXMIrsT1Us1PlbSB"; string cuid = "256641545456156185456489484";//生成guid string getTokenURL = ""; string serverURL = "http://tsn.baidu.com/text2audio"; public StringToAudio() { cuid = Guid.NewGuid().ToString(); getToken(); } #region getToken private void getToken() { getTokenURL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials" + "&client_id=" + apiKey + "&client_secret=" + secretKey; token = GetValue("access_token"); } private string GetValue(string key) { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(getTokenURL); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader1 = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string ssss = reader1.ReadToEnd().Replace("\"", "").Replace("{", "").Replace("}", "").Replace("\n", ""); string[] indexs = ssss.Split(','); foreach (string index in indexs) { string[] _indexs = index.Split(':'); if (_indexs[0] == key) return _indexs[1]; } return ""; } #endregion public string stringToAudio(string data, string fileName) { serverURL += "?tex=" + data + "&lan=zh&cuid=" + cuid + "&ctp=1&tok=" + token; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(serverURL)); request.Timeout = 30000; request.Method = "GET"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (Stream stream = response.GetResponseStream()) { byte[] buffer = new byte[1024]; FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); int count = -1; while (count != 0) { count = stream.Read(buffer,0,buffer.Length); fs.Write(buffer, 0, count); } fs.Flush(); fs.Close(); } } return fileName; } } 
 
}
</pre><pre name="code" class="csharp">
外部调用:
</pre><pre name="code" class="csharp"><pre name="code" class="csharp"><pre name="code" class="csharp">StringToAudio sta = new StringToAudio();
string audioFileName=sta.stringToAudio("测试文本",Application.StartupPath+"\\"+DateTime.Now.ToString("yyyyMMddhhmmssffff")+".mp3");
System.Diagnostics.Process.Start(audioFileName);