基於C# 百度AI和科大汛飛語音合成SDK

1、百度語音合成

百度語音合成C# SDK主要是基於Rest API,須要互聯網調用HTTP接口,Rest API 僅支持最多512個漢字,合成的格式文件爲MP3,沒有其它的格式。若是想離線使用需下載SDK,Android 或IOS。php

一、安裝語音合成 C# SDK

C# SDK 現已開源! https://github.com/Baidu-AIP/dotnet-sdkhtml

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

二、方法一:使用Nuget管理依賴 (推薦)

在NuGet中搜索 Baidu.AI,安裝最新版便可。github

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

三、源程序界面及代碼

   #region 百度語音

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (spinEdit1.Value <= 0)
            {
                spinEdit1.Focus();
                return;
            }
            if (trackBarControl1.Value <= 0)
            {
                trackBarControl1.Focus();
                return;
            }

            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                textBox1.Focus();
                textBox1.Select();
                return;
            }

            // 設置APPID/AK/SK
            var APP_ID = "******";
            var API_KEY = "******";
            var SECRET_KEY = "*****";

            var client = new Baidu.Aip.Speech.Tts(API_KEY, SECRET_KEY);
            client.Timeout = 60000;  // 修改超時時間


            // 可選參數
            var option = new Dictionary<string, object>()
            {
                {"spd", spinEdit1.Value}, // 語速
                {"vol", trackBarControl1.Value}, // 音量
                {"per", comboBoxEdit1.SelectedIndex}  // 發音人,4:情感度丫丫童聲
            };
            var result = client.Synthesis(textBox1.Text, option);

            if (xtraSaveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                if (result.ErrorCode == 0)  // 或 result.Success
                {
                    File.WriteAllBytes(xtraSaveFileDialog1.FileName, result.Data);
                }
            }
        }

        #endregion

 接口參數說明:c#

 

2、科大訊飛語音合成 

 科大訊飛沒有c# SDK,採用WebAPi的形式調用。不過請注意該接口使用的HTTP API協議不支持跨域。api

一、接口調用流程

注: 調用接口前需配置IP白名單,IP白名單規則請參照 IP白名單(因爲我以前沒有設置正確的IP,致使接口調用不成功)能夠在百度裏面輸入IP將會顯示你的互聯網IP跨域

  1. 經過接口密鑰基於MD5計算簽名,將簽名以及其餘參數放在Http Request Header中 。
  2. 將文本數據放在Http Request Body中 。
  3. 向服務器端發送Http請求後,接收服務器端的返回結果。

 

 注: 在控制檯添加服務後,點擊「發音人管理」可自行添加並試用發音人,添加後會顯示該發音人蔘數值,設置參數voice_name爲相應的發音人蔘數值便可。緩存

二、程序界面及源代碼

源代碼服務器

  public class Rootobject
    {
        public string auf { get; set; }
        public string aue { get; set; }
        public string voice_name { get; set; }
        public string speed { get; set; }
        public string volume { get; set; }
        public string pitch { get; set; }
        public string engine_type { get; set; }
        public string text_type { get; set; }
    }
        String Md5(string s)
        {
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(s);
            bytes = md5.ComputeHash(bytes);
            md5.Clear();
            string ret = "";
            for (int i = 0; i < bytes.Length; i++)
            {
                ret += Convert.ToString(bytes[i], 16).PadLeft(2, '0');
            }
            return ret.PadLeft(32, '0');
        }
        #region 把流轉換成緩存流
        MemoryStream StreamToMemoryStream(Stream instream)
        {
            MemoryStream outstream = new MemoryStream();
            const int bufferLen = 4096;
            byte[] buffer = new byte[bufferLen];
            int count = 0;
            while ((count = instream.Read(buffer, 0, bufferLen)) > 0)
            {
                outstream.Write(buffer, 0, count);
            }
            return outstream;
        }
        #endregion
        #region 把緩存流轉換成字節組
        public static byte[] streamTobyte(MemoryStream memoryStream)
        {
            byte[] buffer = new byte[memoryStream.Length];
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.Read(buffer, 0, buffer.Length);
            return buffer;
        }
        #endregion
   private void simpleButton2_Click(object sender, EventArgs e)
        {

            // 應用APPID(必須爲webapi類型應用,並開通語音合成服務,參考帖子如何建立一個webapi應用:http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=36481)
            string appID = "****";
            // 接口密鑰(webapi類型應用開通合成服務後,控制檯--個人應用---語音合成---相應服務的apikey)
            string APIKey = "****";
            // 語音合成webapi接口地址
            String url = "http://api.xfyun.cn/v1/service/v1/tts";
            String bodys;
            // 待合成文本
            string text = memoEdit1.Text;
            // 對要合成語音的文字先用utf-8而後進行URL加密
            byte[] textData = Encoding.UTF8.GetBytes(text);

            text = HttpUtility.UrlEncode(textData);
            bodys = string.Format("text={0}", text);

            //aue = raw, 音頻文件保存類型爲 wav或者pcm
            //aue = lame, 音頻文件保存類型爲 mp3
            string AUE = "lame";

            Rootobject root = new Rootobject();
            root.aue = AUE;
            root.auf = "audio/L16;rate=16000";
            root.speed = speed.Value.ToString();
            root.pitch = pitch.Value.ToString();
            root.volume = volume.Value.ToString();
            root.voice_name = voice_name.Text.Split('-')[0];
            root.engine_type = engine_type.Text.Split('-')[0];
            root.text_type = "text";
            string param = Newtonsoft.Json.JsonConvert.SerializeObject(root);
            // 獲取十位的時間戳
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string curTime = Convert.ToInt64(ts.TotalSeconds).ToString();
            // 對參數先utf-8而後用base64編碼
            byte[] paramData = Encoding.UTF8.GetBytes(param);
            string paraBase64 = Convert.ToBase64String(paramData);
            // 造成簽名
            string checkSum = Md5(APIKey + curTime + paraBase64);
            // 組裝http請求頭
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Headers.Add("X-Param", paraBase64);
            request.Headers.Add("X-CurTime", curTime);
            request.Headers.Add("X-Appid", appID);
            request.Headers.Add("X-CheckSum", checkSum);

            Stream requestStream = request.GetRequestStream();
            StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.GetEncoding("gb2312"));
            streamWriter.Write(bodys);
            streamWriter.Close();

            String htmlStr = string.Empty;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream responseStream = response.GetResponseStream();

            using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
            {
                string header_type = response.Headers["Content-Type"];
                if (header_type == "audio/mpeg")
                {
                    Stream st = response.GetResponseStream();
                    MemoryStream memoryStream = StreamToMemoryStream(st);

                    if (xtraSaveFileDialog2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        // 保存音頻文件地址和音頻格式類型
                        File.WriteAllBytes(xtraSaveFileDialog2.FileName, streamTobyte(memoryStream));
                    }

                    Console.WriteLine(response.Headers);
                    Console.ReadLine();
                }
                else
                {
                    htmlStr = reader.ReadToEnd();
                    Console.WriteLine(htmlStr);
                    Console.ReadLine();
                }
            }
            responseStream.Close();
        }

        #endregion
    }

 經過嘗試百度和科大訊飛兩個語音合成接口,發現科大訊飛語音比較好一些,百度有些詞語會讀錯。

相關文章
相關標籤/搜索