最近要做一个英语学习软件,首先要考虑的就是词库,单词好找,发音比较难解决,分析了市面上几家语音引擎提供商,谷歌是发音最标准的了,下面是采集谷歌单词发音的c#代码。
/// <summary>
/// 去谷歌官方api获取发音并下载到本地,返回音频文件相对路径
/// </summary>
/// <param name="word">单词全拼</param>
/// <returns>返回音频文件相对路径</returns>
private static string makeMp3(string word)
{
try
{
string url = "http://translate.google.com/translate_tts?tl=en&q=" + word;
string k = word.Substring(0, 1);
string path = HttpContext.Current.Server.MapPath("~/wordVolice/") + "\\" + k;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);//在根目录下建立文件夹
}
string filename = path + "\\" + word + ".mp3";
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
return "/wordVolice/" + k + "/" + word + ".mp3";
}
catch {
return null;
}
}