Android TextToSpeech语音播放文本

阅读更多
步骤一、初始化
package com.example.speakdemo2;

import java.util.Locale;

import android.app.Activity;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;

public class Help {
	private Activity activity;
	private TextToSpeech textToSpeech;

	public Help(Activity activity) {
		this.activity = activity;
		textToSpeech = new TextToSpeech(activity,
				new TextToSpeech.OnInitListener() {

					@Override
					public void onInit(int status) {
						if (status == TextToSpeech.SUCCESS) {
							int result = textToSpeech.setLanguage(Locale.US);
							if (result == TextToSpeech.LANG_MISSING_DATA
									|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
								Log.e("MESSAGE", "不支持的语言");
							}

						}

					}
				});

	}

	public void speak(String voice) {
		textToSpeech.speak(voice, TextToSpeech.QUEUE_FLUSH, null);
	}

}


步骤二、文本转语音播放
package com.example.speakdemo2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	Help help;
	EditText editText;
	Button button;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		help = new Help(this);

		editText = (EditText) findViewById(R.id.edit_text);
		button = (Button) findViewById(R.id.btn);
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				help.speak(editText.getText().toString());

			}
		});

	}

}


源码下载请点这里:
  • SpeakDemo2.zip (1012.7 KB)
  • 下载次数: 23

你可能感兴趣的:(android)