Android TextToSpeech简单使用

    如何让Android手机读取文本呢?Android SDK为开发者提供了TTS技术,开发者只需要做简单的调用就可以完成让Android读取文本的功能。

    示例的功能是点击按钮后,朗读TextVeiw中的文本,UI如下:



     对TextToSpeech的实例添加OnInitListener()和OnUtteranceCompletedListener()来实现对TTS状态的监听,并在需要时,添加自己的逻辑代码。这个功能的核心代码如下:

package com.anhuioss.tts;

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.TextView;
import android.widget.Toast;

public class TTSActivity extends Activity implements OnClickListener, OnInitListener {
	
	Button speechButton;
	TextView speechText;
	
	TextToSpeech textToSpeech;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        speechButton = (Button) findViewById(R.id.button1);
        speechText = (TextView) findViewById(R.id.textView1);
        
        speechButton.setOnClickListener(this);
        
        textToSpeech = new TextToSpeech(this, this);
        
    }

	@Override
	public void onClick(View v) {
		if (textToSpeech != null && !textToSpeech.isSpeaking()) {
			textToSpeech.speak(speechText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
		}
	}

	@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) {
				Toast.makeText(this, "Denotes the language data is missing or the language is not supported.", Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		textToSpeech.stop();
		textToSpeech.shutdown();
	}
	
} 

    希望对你有所帮助,如需代码,请点击此处!=^_^=

    参考:http://developer.android.com/reference/android/speech/tts/TextToSpeech.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值