我正在尝试将我的WP7应用程序移植到Android。 我正在使用Bing翻译服务下载和播放特定单词/短语的音频。 如何在安卓中执行此操作?在必应中,流以.wav文件的形式出现。这是我的WP7代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
this.Speak();
}
public void Speak()
{
string appId = "Your ID";
string text = "Speak this for me";
string language = "en";
string uri = "http://api.microsofttranslator.com/v2/Http.svc/Speak?appId=" + appId +
"&text=" + text + "&language=" + language + "&file=speak.wav";
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri(uri));
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null) return;
var sound = e.Result;
Player.Source = null;
string filename = "MyAudio";
using (IsolatedStorageFile userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication())
{
bool fileExists = userStoreForApplication.FileExists(filename);
if (fileExists)
{
userStoreForApplication.DeleteFile(filename);
}
var isolatedStorageFileStream = userStoreForApplication.CreateFile(filename);
using (isolatedStorageFileStream)
{
SaveFile(e.Result, isolatedStorageFileStream);
if (e.Error == null)
{
Player.SetSource(isolatedStorageFileStream);
}
}
}
}
public static void SaveFile(System.IO.Stream input, System.IO.Stream output)
{
try
{
byte[] buffer = new byte[32768];
while (true)
{
int read = input.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
return;
}
output.Write(buffer, 0, read);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
void mysound_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
MessageBox.Show(e.ErrorException.Message);
}
void mysound_MediaOpened(object sender, RoutedEventArgs e)
{
Player.Play();
}
我以为我只会删除有关执行HTTP请求和下载文件的通用响应,但是我遇到的更麻烦的事情是Azure想要如何进行身份验证Microsoft。显然,不推荐使用应用程序 ID,他们的 API 对请求标头和参数非常挑剔。
无论如何,我建议从编写处理执行HttpURLConnection
的AsyncTask
开始。我最终得到:
/**
* Tailor-made HTTP request for Microsoft Azure, downloading a file to a
* specified location.
*/
private class HttpDownloadFile extends AsyncTask<String, Integer, String> {
private String mDir;
@Override
protected String doInBackground(String... params) {
if (params.length < 2) {
throw new IllegalArgumentException(
"Two arguments required for "
+ getClass().getSimpleName());
}
String response = null;
String uri = params[0];
String query = params[1];
try {
if (query.length() > 0) {
uri += "?" + query;
}
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
if (params.length > 2) {
connection.setRequestProperty("Authorization", "Bearer "
+ params[2]);
}
connection.connect();
int fileLength = connection.getContentLength();
String charset = PREFERRED_CHARSET;
if (connection.getContentEncoding() != null) {
charset = connection.getContentEncoding();
}
InputStream input;
OutputStream output;
boolean isError = false;
try {
input = connection.getInputStream();
output = new FileOutputStream(mDir);
} catch (IOException e) {
input = connection.getErrorStream();
output = new ByteArrayOutputStream();
isError = true;
}
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
if (!isError) {
response = mDir;
} else {
response = ((ByteArrayOutputStream) output).toString(charset);
Log.e(TAG, response);
response = null;
}
output.close();
input.close();
} catch (Exception e) {
Log.e(TAG, "Failed requesting " + uri, e);
}
return response;
}
}
然后,您可以使用正确的参数执行任务:
HttpDownloadFile task = new HttpDownloadFile();
task.execute(
getString(R.string.url_speak),
getString(R.string.url_speak_query,
text, toLanguage, file),
accessToken,
Environment.getExternalStorageDirectory().getPath()
+ "/temp.wav");
我的strings.xml
包含:
<string
name="url_speak"
formatted="false"
translate="false">http://api.microsofttranslator.com/v2/Http.svc/Speak</string>
<string
name="url_speak_query"
formatted="false"
translate="false">text=%s&language=%s&file=%s</string>
不幸的是,这意味着您必须编写代码才能获取已完成的身份验证令牌。不用担心!我也为所有这些编写了完整的代码:
-
MainActivity.java
-
strings.xml
对我来说似乎很简单,首先使用HttpUrlConnection
若要调用 Web 服务,然后将响应作为 WAV 文件处理,可以先将文件保存在本地,然后将其加载到Mediaplayer
实例中,也可以直接将其作为实时流加载。