我正在编写一些代码,使用简单的GET方法将Google翻译的文本转换为语音,我很困惑为什么它不起作用。例如,单击...
http://translate.google.com/translate_tts?tl=en&q=hello
我写了一些C#代码,据我所知,它应该可行,但事实并非如此。如果Google阻止请求,我会徘徊吗?从控制台尝试这个给我一个403错误(“禁止”)。
以下是代码。如果有人可以提供帮助,我会很感激!
namespace WCTest
{
public partial class MainPage : PhoneApplicationPage
{
string searchString = "http://translate.google.com/translate_tts?tl=en&q=hello";
// Constructor
public MainPage()
{
InitializeComponent();
WebClient client = new WebClient();
client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" + " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
client.Headers["Referrer"] = "http://brillisoft.com";
client.OpenReadCompleted += (s, e) =>
{
if (e.Error == null)
{
Stream audio = e.Result;
mediaElement1.SetSource(audio);
mediaElement1.Play();
}
};
client.OpenReadAsync(new Uri(searchString));
}
}
}
更新...... 3月10日......
传奇继续......以下代码适用于我的一些同事的计算机,但不适用于我的...这可能导致什么?如果这对您有用,请告诉我,如果您认为有必要将文件保存到IsolatedStorage ...
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
string searchString = "http://translate.google.com/translate_tts?tl=en&q=it+works";
private void button1_Click(object sender, RoutedEventArgs e)
{
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0)" + " (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
client.Headers[HttpRequestHeader.Referer] = "http://translate.google.com";
client.OpenReadCompleted += (s, ex) =>
{
if (ex.Error == null)
{
using (var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists("hello3.mp3"))
{
store.DeleteFile("hello3.mp3");
}
using (var fs = new System.IO.IsolatedStorage.IsolatedStorageFileStream("hello3.mp3", System.IO.FileMode.Create, store))
{
byte[] bytesInStream = new byte[ex.Result.Length];
ex.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);
fs.Write(bytesInStream, 0, bytesInStream.Length);
fs.Flush();
mediaElement1.SetSource(fs);
}
}
mediaElement1.Play();
}
};
client.OpenReadAsync(new Uri(searchString));
}
}
}