Android TTS的简单应用
MIanActivity的代码
package com.ttsactivity;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
//先导入在实现接口,在接口直接输入TextToSpeech;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener,OnClickListener{
private TextToSpeech tts;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
Button button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textview);
button.setOnClickListener(this);
}
//继承接口实现的方法
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.US);
if(result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED){
Toast.makeText(this, "语言不存在", Toast.LENGTH_SHORT).show();
}
}
}
//读取内容
@Override
public void onClick(View view) {
tts.speak(textView.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
}
布局文件的代码
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="朗读文本" />
</LinearLayout>
资源文件的代码,读的内容所在地
最重要的是第三局,那是我要读的内容
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TTSActivity</string>
<string name="action_settings">Settings</string>
<string name="text">to the world you mabe one person,but to one person you mabe the world</string>
</resources>
最后截图来一张