Android 自动朗读(TTS)

来源:互联网 发布:淘宝 类目销量排行 编辑:程序博客网 时间:2024/06/11 10:05

 在Android应用中,有时候需要朗读一些文本内容,今天介绍一下Android系统自带的朗读TextToSpeech(TTS)。自动朗读支持可以对指定文本内容进行朗读,还可以把文本对应的音频录制成音频文件。Android的自动朗读支持主要通过TextToSpeech来完成,该类提供了如下构造器: 

TextToSpeech(Context context, TextToSpeech.OnInitListenerlistener)

当创建TextToSpeech对象时,必须先提供一个OnInitListener监听器---该监听器负责监听TextToSpeech的初始化结果。
 一旦获得了TextToSpeech对象后,接下来可调用TextToSpeech的setLanguage(Localeloc)方法设置发声引擎应使用的语言、国家选项。

 如果调用setLanguage(Localeloc)的返回值是"TextToSpeech.LANG_COUNTRY_AVAILABLE"说明当前TTS系统可以支持所设置的语言、国家。

  TTS有两个方法来朗读:

  speak(String text,int queueMode,HashMapparams)、synthesizeToFile(String text,HashMap params,StringfileName);

  speak和synthesizeToFile的区别是一个后者可以把音频保存下来。

 params参数:TextToSpeech.QUEUE_ADD,TextToSpeech.QUEUE_FLSH,前者调用speak方法时,会把新的发音任务添加到当前发音任务队列之后,后者直接中断当前发音任务。

下面介绍一下使用TextToSpeech的步骤:

 1、创建TextToSpeech对象,创建时传入OnInitListener监听器监听创建是否成功。

 2、设置TextToSpeech所使用语言、国家,通过返回值判断TTS是否支持该语言、国家。

  3、调用speak或synthesizeToFile。

  4、关闭TTS,回收资源。

  下面上一个实例:

public class Speech extends Activity
{
 TextToSpeech tts;
 EditText editText;
 Button speech;
 Button record;

 @Override
 public void onCreate(BundlesavedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  // 初始化TextToSpeech对象
  tts = new TextToSpeech(this,new OnInitListener()
  {
   @Override
   public voidonInit(int status)
   {
    //如果装载TTS引擎成功
    if(status == TextToSpeech.SUCCESS)
    {
     //设置使用美式英语朗读
     intresult = 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(newOnClickListener()
  {
   @Override
   public voidonClick(View arg0)
   {
    //执行朗读
    tts.speak(editText.getText().toString(),
     TextToSpeech.QUEUE_ADD,null);
   }
  });
  record.setOnClickListener(newOnClickListener()
  {
   @Override
   public voidonClick(View arg0)
   {
    //将朗读文本的音频记录到指定文件
    tts.synthesizeToFile(editText.getText().toString(),null,
     "/mnt/sdcard/sound.wav");
    Toast.makeText(Speech.this,"声音记录成功!", 50000).show();
   }
  });
 }
 @Override
 public void onDestroy()
 {
  // 关闭TextToSpeech对象
  if (tts != null)
  {
   tts.shutdown();
  }
 }
}