马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

基于C# 百度AI和科大汛飞语音合成SDK

[复制链接]
查看2277 | 回复0 | 2019-8-13 17:59:50 | 显示全部楼层 |阅读模式

一、百度语音合成

百度语音合成C# SDK主要是基于Rest API,必要互联网调用HTTP接口,Rest API 仅支持最多512个汉字,合成的格式文件为MP3,没有其它的格式。如果想离线使用需下载SDK,Android 或IOS。

1、安装语音合成 C# SDK

C# SDK 现已开源! https://github.com/Baidu-AIP/dotnet-sdk

** 支持平台:.Net Framework 3.5 4.0 4.5, .Net Core 2.0 **

2、方法一:使用Nuget管理依赖 (推荐)

在NuGet中搜索 Baidu.AI,安装最新版即可。

packet地址 https://www.nuget.org/packages/Baidu.AI/

3、源程序界面及代码

180012cclcp9nn88qnxp99.png

  1. #region 百度语音
  2. private void simpleButton1_Click(object sender, EventArgs e)
  3. {
  4. if (spinEdit1.Value <= 0)
  5. {
  6. spinEdit1.Focus();
  7. return;
  8. }
  9. if (trackBarControl1.Value <= 0)
  10. {
  11. trackBarControl1.Focus();
  12. return;
  13. }
  14. if (string.IsNullOrEmpty(textBox1.Text.Trim()))
  15. {
  16. textBox1.Focus();
  17. textBox1.Select();
  18. return;
  19. }
  20. // 设置APPID/AK/SK
  21. var APP_ID = "******";
  22. var API_KEY = "******";
  23. var SECRET_KEY = "*****";
  24. var client = new Baidu.Aip.Speech.Tts(API_KEY, SECRET_KEY);
  25. client.Timeout = 60000; // 修改超时时间
  26. // 可选参数
  27. var option = new Dictionary<string, object>()
  28. {
  29. {"spd", spinEdit1.Value}, // 语速
  30. {"vol", trackBarControl1.Value}, // 音量
  31. {"per", comboBoxEdit1.SelectedIndex} // 发音人,4:情感度丫丫童声
  32. };
  33. var result = client.Synthesis(textBox1.Text, option);
  34. if (xtraSaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  35. {
  36. if (result.ErrorCode == 0) // 或 result.Success
  37. {
  38. File.WriteAllBytes(xtraSaveFileDialog1.FileName, result.Data);
  39. }
  40. }
  41. }
  42. #endregion
复制代码

接口参数说明:

180012vrncnji07n7zexer.png

二、科大讯飞语音合成

科大讯飞没有c# SDK,采用WebAPi的形式调用。不过请注意该接口使用的HTTP API协议不支持跨域。

1、接口调用流程

注: 调用接口前需配置IP白名单,IP白名单规则请参照 IP白名单。(由于我之前没有设置正确的IP,导致接口调用不乐成)可以在百度里面输入IP将会显示你的互联网IP

  1. 通过接口密钥基于MD5计算签名,将签名以及其他参数放在Http Request Header中 。
  2. 将文本数据放在Http Request Body中 。
  3. 向服务器端发送Http请求后,接收服务器端的返回结果。

180013j6jl6661pogh6g6w.png

注: 在控制台添加服务后,点击“发音人管理”可自行添加并试用发音人,添加后会显示该发音人参数值,设置参数voice_name为相应的发音人参数值即可。

2、程序界面及源代码

180013jo7t9o7st8z81t8j.png

源代码

  1. public class Rootobject
  2. {
  3. public string auf { get; set; }
  4. public string aue { get; set; }
  5. public string voice_name { get; set; }
  6. public string speed { get; set; }
  7. public string volume { get; set; }
  8. public string pitch { get; set; }
  9. public string engine_type { get; set; }
  10. public string text_type { get; set; }
  11. }
复制代码
  1. String Md5(string s)
  2. {
  3. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  4. byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
  5. bytes = md5.ComputeHash(bytes);
  6. md5.Clear();
  7. string ret = "";
  8. for (int i = 0; i < bytes.Length; i++)
  9. {
  10. ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
  11. }
  12. return ret.PadLeft(32, '0');
  13. }
复制代码
  1. #region 把流转换成缓存流
  2. MemoryStream StreamToMemoryStream(Stream instream)
  3. {
  4. MemoryStream outstream = new MemoryStream();
  5. const int bufferLen = 4096;
  6. byte[] buffer = new byte[bufferLen];
  7. int count = 0;
  8. while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
  9. {
  10. outstream.Write(buffer, 0, count);
  11. }
  12. return outstream;
  13. }
  14. #endregion
复制代码
  1. #region 把缓存流转换成字节组
  2. public static byte[] streamTobyte(MemoryStream memoryStream)
  3. {
  4. byte[] buffer = new byte[memoryStream.Length];
  5. memoryStream.Seek(0, SeekOrigin.Begin);
  6. memoryStream.Read(buffer, 0, buffer.Length);
  7. return buffer;
  8. }
  9. #endregion
复制代码
  1. private void simpleButton2_Click(object sender, EventArgs e)
  2. {
  3. // 应用APPID(必须为webapi类型应用,并开通语音合成服务,参考帖子如何创建一个webapi应用:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
  4. string appID = "****";
  5. // 接口密钥(webapi类型应用开通合成服务后,控制台--我的应用---语音合成---相应服务的apikey)
  6. string APIKey = "****";
  7. // 语音合成webapi接口地址
  8. String url = "http://api.xfyun.cn/v1/service/v1/tts";
  9. String bodys;
  10. // 待合成文本
  11. string text = memoEdit1.Text;
  12. // 对要合成语音的文字先用utf-8然后进行URL加密
  13. byte[] textData = Encoding.UTF8.GetBytes(text);
  14. text = HttpUtility.UrlEncode(textData);
  15. bodys = string.Format("text={0}", text);
  16. //aue = raw, 音频文件生存类型为 wav或者pcm
  17. //aue = lame, 音频文件生存类型为 mp3
  18. string AUE = "lame";
  19. Rootobject root = new Rootobject();
  20. root.aue = AUE;
  21. root.auf = "audio/L16;rate=16000";
  22. root.speed = speed.Value.ToString();
  23. root.pitch = pitch.Value.ToString();
  24. root.volume = volume.Value.ToString();
  25. root.voice_name = voice_name.Text.Split('-')[0];
  26. root.engine_type = engine_type.Text.Split('-')[0];
  27. root.text_type = "text";
  28. string param = Newtonsoft.Json.JsonConvert.SerializeObject(root);
  29. // 获取十位的时间戳
  30. TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
  31. string curTime = Convert.ToInt64(ts.TotalSeconds).ToString();
  32. // 对参数先utf-8然后用base64编码
  33. byte[] paramData = Encoding.UTF8.GetBytes(param);
  34. string paraBase64 = Convert.ToBase64String(paramData);
  35. // 形成签名
  36. string checkSum = Md5(APIKey + curTime + paraBase64);
  37. // 组装http请求头
  38. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  39. request = (HttpWebRequest)WebRequest.Create(url);
  40. request.Method = "POST";
  41. request.ContentType = "application/x-www-form-urlencoded";
  42. request.Headers.Add("X-Param", paraBase64);
  43. request.Headers.Add("X-CurTime", curTime);
  44. request.Headers.Add("X-Appid", appID);
  45. request.Headers.Add("X-CheckSum", checkSum);
  46. Stream requestStream = request.GetRequestStream();
  47. StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.GetEncoding("gb2312"));
  48. streamWriter.Write(bodys);
  49. streamWriter.Close();
  50. String htmlStr = string.Empty;
  51. HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  52. Stream responseStream = response.GetResponseStream();
  53. using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
  54. {
  55. string header_type = response.Headers["Content-Type"];
  56. if (header_type == "audio/mpeg")
  57. {
  58. Stream st = response.GetResponseStream();
  59. MemoryStream memoryStream = StreamToMemoryStream(st);
  60. if (xtraSaveFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  61. {
  62. // 生存音频文件地址和音频格式类型
  63. File.WriteAllBytes(xtraSaveFileDialog2.FileName, streamTobyte(memoryStream));
  64. }
  65. Console.WriteLine(response.Headers);
  66. Console.ReadLine();
  67. }
  68. else
  69. {
  70. htmlStr = reader.ReadToEnd();
  71. Console.WriteLine(htmlStr);
  72. Console.ReadLine();
  73. }
  74. }
  75. responseStream.Close();
  76. }
  77. #endregion
  78. }
复制代码

通过尝试百度和科大讯飞两个语音合成接口,发现科大讯飞语音比较好一些,百度有些词语会读错。


来源:https://www.cnblogs.com/w2011/p/11328023.html
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则