Android的数据存储和IO - 自动朗读(TTS)
自动朗读又是Android提供的另一种另类的IO,蛮不错的哦,支持对指定文本内容进朗读,学习完这个内容我立马就让它朗读:wwj is a good man.作为一个自我满足。
创建项目:Speech
运行效果:
- package wwj.speech;
- 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.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.EditText;
- import android.widget.Toast;
- public class Speech extends Activity {
- TextToSpeech tts;
- EditText editText;
- Button speech;
- Button record;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //初始化TextToSpeech对象
- tts = new TextToSpeech(this, new OnInitListener() {
- public void onInit(int status) {
- // TODO Auto-generated method stub
- //如果装载TTS引擎成功
- if(status == TextToSpeech.SUCCESS){
- //设置使用美式英语朗读
- int result = tts.setLanguage(Locale.US);
- //如果不支持所设置的语言
- if(result != TextToSpeech.LANG_COUNTRY_AVAILABLE
- && result != TextToSpeech.LANG_AVAILABLE){
- Toast.makeText(Speech.this, "TTS暂时不支持这种语言的朗读。", 50000).show();
- }
- }
- }
- });
- editText = (EditText)findViewById(R.id.txt);
- speech = (Button) findViewById(R.id.speech);
- record = (Button) findViewById(R.id.record);
- speech.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //执行朗读
- tts.speak(editText.getText().toString(), TextToSpeech.QUEUE_ADD, null);
- }
- });
- record.setOnClickListener(new OnClickListener() {
- public void onClick(View v) {
- // TODO Auto-generated method stub
- //将朗读文本的音频记录到指定文件
- tts.synthesizeToFile(editText.getText().toString(), null, "/mnt/sdcard/sound.wav");
- Toast.makeText(Speech.this, "声音记录成功! ", 50000).show();
- }
- });
- }
- @Override
- protected void onDestroy() {
- // TODO Auto-generated method stub
- //关闭TextToSpeech对象
- if(tts != null){
- tts.shutdown();
- }
- super.onDestroy();
- }
- }