1 //英文字符串转语音;中文需要第三方jar包
2 public class MainActivity extends Activity implements
3 TextToSpeech.OnInitListener {
4 private TextToSpeech tts;
5 private TextView textView;
6
7 @Override
8 protected void onCreate(Bundle savedInstanceState) {
9 super.onCreate(savedInstanceState);
10 setContentView(R.layout.fragment_main);
11 tts = new TextToSpeech(this, this);
12 textView = (TextView) findViewById(R.id.textView1);
13 Button button = (Button) findViewById(R.id.button1);
14 button.setOnClickListener(new OnClickListener() {
15
16 @Override
17 public void onClick(View v) {
18 // TODO Auto-generated method stub
19 tts.speak(textView.getText().toString(),
20 TextToSpeech.QUEUE_FLUSH, null);
21 }
22 });
23
24 }
25
26 @Override
27 public void onInit(int status) {
28 // TODO Auto-generated method stub
29 if (status == TextToSpeech.SUCCESS) {
30 int result = tts.setLanguage(Locale.US);
31 if (result == TextToSpeech.LANG_MISSING_DATA
32 || result == TextToSpeech.LANG_NOT_SUPPORTED) {
33 Toast.makeText(MainActivity.this, "语言不支持", 0).show();
34 }
35 }
36 }
37
38 }