c# 百度语音合成

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

开始代码:

首先是stringtoaudio类

这里使用的是我的百度语音识别appkey,可以自己去申请,很简单,请参考之前关于语音转文字的帖子或者上面的传送门

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; } } 
  
 
  
}
 
  
外部调用:
StringToAudio sta = new StringToAudio();
string audioFileName=sta.stringToAudio("测试文本",Application.StartupPath+"\\"+DateTime.Now.ToString("yyyyMMddhhmmssffff")+".mp3");
System.Diagnostics.Process.Start(audioFileName);
 
  
 
  

你可能感兴趣的:(桌面应用)