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; }
///
/// 首选翻译
///
[DataMember(Name = "translation")]
public List
///
/// 基本释义
///
[DataMember(Name = "basic")]
public TranslationBasicData BasicTranslation { get; set; }
/////
///// 网络释义,该结果不一定存在,暂时不使用
/////
//[DataMember(Name = "web")]
//public TranslationWebData WebTranslation { get; set; }
}
///
/// 基本释义
///
[DataContract]
public class TranslationBasicData
{
[DataMember(Name = "phonetic")]
public string Phonetic { get; set; }
///
/// 英式发音
///
[DataMember(Name = "uk-phonetic")]
public string UkPhonetic { get; set; }
///
/// 美式发音
///
[DataMember(Name = "us-phonetic")]
public string UsPhonetic { get; set; }
///
/// 翻译
///
[DataMember(Name = "explains")]
public List
}
///
/// 网络释义
///
[DataContract]
public class TranslationWebData
{
[DataMember(Name = "key")]
public string Key { get; set; }
[DataMember(Name = "value")]
public List
}
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 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
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 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;
}
}
}