Android TextToSpeech
TextToSpeech
Support from API 19(4.4)
Chinese is not supported.
I tried English(US), Japanese, Germany
Sample
English, Japanese switch
Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
>
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="@string/write"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="188dp"
android:layout_marginRight="67dp"
android:onClick="speakText"
android:text="@string/text1" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="81dp"
android:ems="10" >
<requestFocus />
</EditText>
<Switch
android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/editText1"
android:layout_marginBottom="20dp"
android:layout_centerHorizontal="true"
android:textOn="US"
android:textOff="Jp"
android:text="Language" />
</RelativeLayout>
Code
public class MainActivity extends Activity {
private TextToSpeech tts;
private EditText write;
private Switch mySwitch;
private Button textTo;
private boolean loaded;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loaded = false;
write = (EditText)findViewById(R.id.editText1);
textTo = (Button)findViewById(R.id.button1);
mySwitch = (Switch)findViewById(R.id.mySwitch);
mySwitch.setChecked(true);
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (loaded) {
if (isChecked) {
tts.setLanguage(Locale.US);
}
else {
tts.setLanguage(Locale.JAPAN);
}
}
}
});
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
loaded = true;
tts.setLanguage(Locale.US);
//tts.setLanguage(Locale.GERMANY);
}
textTo.setEnabled(loaded);
}
});
}
@Override
protected void onPause() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onPause();
}
public void speakText(View view){
String toSpeak = write.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak,
Toast.LENGTH_SHORT).show();
tts.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
}

