3

WP7アプリをAndroidに移植しようとしています。私はBing翻訳サービスを使用して、特定の単語/フレーズのオーディオをダウンロードして再生していました。どうすれば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();  
    } 
4

2 に答える 2

1

HTTP リクエストの実行とファイルのダウンロードに関する一般的な応答を削除するだけだと思っていましたが、Microsoft Azure がどのように認証を行いたいかという問題に遭遇しました。明らかに、アプリ 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
于 2012-09-03T20:37:11.793 に答える
0

これは私にはかなり簡単に思えます。最初HttpUrlConnection に Web サービスを呼び出すために使用し、次に応答を wav ファイルとして処理します。最初にファイルをローカルに保存してから Mediaplayerインスタンスにロードするか、次のように直接ロードすることができます。ライブストリーム。

于 2012-09-03T12:29:00.173 に答える