鸟语天空
TextToSpeak
post by:追风剑情 2016-8-1 15:36
package com.test.androidtest;

import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
/**
 * 文本转语音测试
 */
public class TextToSpeakActivity extends Activity {
	
	int TTS_DATA_CHECK = 1;
	boolean ttsIsInit = false;
	TextToSpeech tts = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_shap_gradient);
		
		//通过启动一个活动来检查TTS库
		Intent intent = new Intent(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(intent, TTS_DATA_CHECK);
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data){
		if(requestCode == TTS_DATA_CHECK){
			//如果已安装了语音数据
			if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
				Toast.makeText(this, "已安装了语音数据", Toast.LENGTH_SHORT);
				tts = new TextToSpeech(this, new TextToSpeech.OnInitListener(){
					@Override
					public void onInit(int status) {
						if(status == TextToSpeech.SUCCESS){
							Toast.makeText(TextToSpeakActivity.this, "语音数据初始化完毕", Toast.LENGTH_SHORT);
							ttsIsInit = true;
							//如果支持英式英语,则设置成英式英语。
							if(tts.isLanguageAvailable(Locale.UK) >= 0)
								tts.setLanguage(Locale.UK);
							tts.setPitch(0.8f);//设置音高
							tts.setSpeechRate(1.1f);//设置音速
							speak();//说话
						}
					}
				});
			}else{
				Toast.makeText(this, "安装语音数据", Toast.LENGTH_SHORT);
				//安装语音数据
				Intent intentVoice = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivityForResult(intentVoice, TTS_DATA_CHECK);
			}
		}
	}
	
	private void speak(){
		if(tts != null && ttsIsInit){
			tts.speak("Hello, Android", TextToSpeech.QUEUE_ADD, null);
		}
	}
	
	@Override
	public void onDestroy(){
		if(null != tts){
			tts.stop();//停止
			tts.shutdown();//释放tts资源
		}
		super.onDestroy();
	}
}

 

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容