Android 輕松實現語音朗讀


語音朗讀,這是一個很好的功能,可以實現一些客戶的特殊要求。在Android 實現主意功能只需要幾段簡單的代碼即可完成。

 

 

在Android 中使用語音朗讀功能 只需要使用此類 TextToSpeech ,該類實現了很多關於語音的功能,使用該類必須為其設置語言,支持語言列表位於java.util類里的Local 類,具體如下:

屏幕問題,顯示不足,大家可以去SDK查看。雖然支持眾多主意列表,可是貌似Android 內置語音朗讀的語言種類並不多,是不是以后得在寫系統的時候編進去還是怎么樣,這個不知所以然,目前我只測試了English 和 Chinese。 English 是可行的,Chinese 失敗了。OK ,廢話不多說, 上全部實現代碼:

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package com.terry;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class speechActivity extends Activity {
    private TextToSpeech mSpeech;
    private Button btn;

    private EditText mEditText;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btn = (Button) findViewById(R.id.Button01);
        mEditText = (EditText) findViewById(R.id.EditText01);
        btn.setEnabled(false);
        mSpeech = new TextToSpeech(this, new OnInitListener() {

            @Override
            public void onInit(int status) {
                // TODO Auto-generated method stub
                if (status == TextToSpeech.SUCCESS) {
                    int result = mSpeech.setLanguage(Locale.ENGLISH);
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("lanageTag", "not use");
                    } else {
                        btn.setEnabled(true);
                        mSpeech.speak("i love you", TextToSpeech.QUEUE_FLUSH,
                                null);
                    }
                }
            }
        });

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mSpeech.speak(mEditText.getText().toString(),
                        TextToSpeech.QUEUE_FLUSH, null);
            }
        });

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (mSpeech != null) {
            mSpeech.stop();
            mSpeech.shutdown();
        }
        super.onDestroy();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM