C# dotnetCore調用有道雲翻譯

using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;
using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace zhiyun_csharp_demo
{
    public enum LanguageType
    {
        zh,//中文    
        en,//英文    
        ja,//日文    
        ko,//韓文    
        fr,//法文    
        es,//西班牙文
        pt,//葡萄牙文
        it,//意大利文
        ru,//俄文    
        vi,//越南文    
        de,//德文    
        ar,//阿拉伯文
        id,//印尼文    
        auto,//自動識別
    }
    [DataContract]
    public class YouDaoTranslationResponse
    {
        [DataMember(Name = "errorCode")]
        public string ErrorCode { get; set; }

        [DataMember(Name = "query")]
        public string QueryText { get; set; }

        [DataMember(Name = "speakUrl")]
        public string InputSpeakUrl { get; set; }

        [DataMember(Name = "tSpeakUrl")]
        public string TranslationSpeakUrl { get; set; }

        /// <summary>
        /// 首選翻譯
        /// </summary>
        [DataMember(Name = "translation")]
        public List<string> FirstTranslation { get; set; }

        /// <summary>
        /// 基本釋義
        /// </summary>
        [DataMember(Name = "basic")]
        public TranslationBasicData BasicTranslation { get; set; }

        ///// <summary>
        ///// 網絡釋義,該結果不一定存在,暫時不使用
        ///// </summary>
        //[DataMember(Name = "web")]
        //public TranslationWebData WebTranslation { get; set; }
    }

    /// <summary>
    /// 基本釋義
    /// </summary>
    [DataContract]
    public class TranslationBasicData
    {
        [DataMember(Name = "phonetic")]
        public string Phonetic { get; set; }

        /// <summary>
        /// 英式發音
        /// </summary>
        [DataMember(Name = "uk-phonetic")]
        public string UkPhonetic { get; set; }

        /// <summary>
        /// 美式發音
        /// </summary>
        [DataMember(Name = "us-phonetic")]
        public string UsPhonetic { get; set; }

        /// <summary>
        /// 翻譯
        /// </summary>
        [DataMember(Name = "explains")]
        public List<string> Explains { get; set; }
    }

    /// <summary>
    /// 網絡釋義
    /// </summary>
    [DataContract]
    public class TranslationWebData
    {
        [DataMember(Name = "key")]
        public string Key { get; set; }

        [DataMember(Name = "value")]
        public List<string> Explains { get; set; }
    }


    class FanyiV3DemoInternalTest
    {

        public static string appKey = "";
        public static string appSecret = "";
        //官方文檔:http://ai.youdao.com/docs/doc-trans-api.s#p08
        public static void Main()
        { 
            var source= "你叫什麼名字,我對你一見鍾情";
            Console.WriteLine("原文:"+source);
            Console.WriteLine("譯文:");
            var names= Enum.GetNames(typeof(LanguageType));
            for (int i = 0; i < names.Length; i++)
            {
                var result = Translate(source, LanguageType.zh, names[i]);
                Console.WriteLine(names[i] + ":" + result);
            }

            Console.ReadKey();
        }
        public static string Translate(string src,LanguageType fromType, string toType) {

            Dictionary<String, String> dic = new Dictionary<String, String>();
            string url = "https://openapi.youdao.com/api";
            string q = src;

            string salt = DateTime.Now.Millisecond.ToString();
            dic.Add("from", fromType.ToString());
            dic.Add("to", toType.ToString());
            dic.Add("signType", "v3");
            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc));
            long millis = (long)ts.TotalMilliseconds;
            string curtime = Convert.ToString(millis / 1000);
            dic.Add("curtime", curtime);
            string signStr = appKey + Truncate(q) + salt + curtime + appSecret; ;
            string sign = ComputeHash(signStr, new SHA256CryptoServiceProvider());
            dic.Add("q", System.Web.HttpUtility.UrlEncode(q));
            dic.Add("appKey", appKey);
            dic.Add("salt", salt);
            dic.Add("sign", sign);

            string resutl = Post(url, dic);
            if (resutl != null)
            {
                var youDaoTranslationResponse = JsonConvert.DeserializeObject<YouDaoTranslationResponse>(resutl);
                
                return youDaoTranslationResponse.FirstTranslation[0];
            }
            return null;
        }
        protected static string ComputeHash(string input, HashAlgorithm algorithm)
        {
            Byte[] inputBytes = Encoding.UTF8.GetBytes(input);
            Byte[] hashedBytes = algorithm.ComputeHash(inputBytes);
            return BitConverter.ToString(hashedBytes).Replace("-", "");
        }

        protected static string Post(string url, Dictionary<String, String> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            if (resp.ContentType.ToLower().Equals("audio/mp3"))
            {
                SaveBinaryFile(resp, "合成的音頻存儲路徑");
            }
            else
            {
                Stream stream = resp.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
              //  Console.WriteLine(result);
                return result;
            }
            return null;
        }

        protected static string Truncate(string q)
        {
            if (q == null)
            {
                return null;
            }
            int len = q.Length;
            return len <= 20 ? q : (q.Substring(0, 10) + len + q.Substring(len - 10, 10));
        }

        private static bool SaveBinaryFile(WebResponse response, string FileName)
        {
            string FilePath = FileName + DateTime.Now.Millisecond.ToString() + ".mp3";
            bool Value = true;
            byte[] buffer = new byte[1024];

            try
            {
                if (File.Exists(FilePath))
                    File.Delete(FilePath);
                Stream outStream = System.IO.File.Create(FilePath);
                Stream inStream = response.GetResponseStream();

                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0)
                        outStream.Write(buffer, 0, l);
                }
                while (l > 0);

                outStream.Close();
                inStream.Close();
            }
            catch
            {
                Value = false;
            }
            return Value;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章