▼Androidメモ▼
音声合成

音声合成を行うプログラムを作成する。



ソースコード
TextToSpeechEx.java
package net.npaka.texttospeechex;
import java.util.Locale;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

//音声合成
public class TextToSpeechEx extends Activity 
    implements View.OnClickListener, TextToSpeech.OnInitListener {
    private EditText     editText;//エディットテキスト
    private Button       button;  //ボタン
    private TextToSpeech tts;     //TTS
    
    //アプリの初期化
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        //レイアウトの生成
        LinearLayout layout=new LinearLayout(this);
        layout.setBackgroundColor(Color.rgb(255,255,255));
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);       
        
        //エディットテキストの生成
        editText=new EditText(this);
        editText.setText("This is TEST!",
            EditText.BufferType.NORMAL);
        setLLParams(editText,240,50);
        layout.addView(editText);
        
        //ボタンの生成
        button=new Button(this);
        button.setText("Speech");
        button.setOnClickListener(this);
        setLLParams(button);  
        layout.addView(button);
        
        //TTSの生成
        tts=new TextToSpeech(this,this);
    }

    //アプリ開始時に呼ばれる
    public void onInit(int status) {
        if (status==TextToSpeech.SUCCESS) {
        	//ロケールの指定
            Locale locale=Locale.ENGLISH;
            if (tts.isLanguageAvailable(locale)>=
            	TextToSpeech.LANG_AVAILABLE) {
                tts.setLanguage(locale);
            }
        }
    }

    //アプリ終了時に呼ばれる
    protected void onDestroy() {
        super.onDestroy();
        
        //TTSの終了
        if (tts!=null) tts.shutdown();
    }

    //ボタンクリックイベントの処理
    public void onClick(View v) {
        String str=editText.getText().toString();
        if (str.length()>0) {
        	//スピーチの停止
            if (tts.isSpeaking()) tts.stop();
            
            //スピーチの再生
            tts.setSpeechRate((float)(100.0f /100.0f));
            tts.speak(str,TextToSpeech.QUEUE_FLUSH,null);
        }        
    }    
    
    //ライナーレイアウトのパラメータ指定
    private static void setLLParams(View view) {
        view.setLayoutParams(new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));
    }  

    //ライナーレイアウトのパラメータ指定
    private static void setLLParams(View view,int w,int h) {
        view.setLayoutParams(new LinearLayout.LayoutParams(w,h));
    }
}



−戻る−