如何使用Bing翻译服务为Android上的特定单词播放音频?

问题描述:

我想将我的WP7应用移植到android。我正在使用Bing翻译服务下载&播放特定单词/短语的音频。我怎么能在android中做到这一点?在bing中,流将以.wav文件的形式出现。这里是我的WP7代码:如何使用Bing翻译服务为Android上的特定单词播放音频?

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(); 
    } 
+0

? – Arveen

这看起来非常简单的我,第一次使用HttpUrlConnection 进行调用Web服务,然后处理响应为WAV文件,要么你可以先保存文件然后将其加载到Mediaplayer实例中,或者直接将其作为实时流加载。

我想我只是放弃了关于执行HTTP请求和下载文件的通用响应,但我遇到的更麻烦的事情是Microsoft Azure如何执行身份验证。显然,使用App ID已被弃用,其API对请求标头和参数极其挑剔。

在任何情况下,我建议先写一个AsyncTask来处理执行HttpURLConnection。我结束了:

/** 
* 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&amp;language=%s&amp;file=%s</string> 

不幸的是,这意味着你必须代码用于获取已经完成的认证令牌。别担心!我写的完整代码所有这一切,太:

  1. MainActivity.java
  2. strings.xml
你在Android的有什么问题