Friday, December 26, 2014

Text to speech in android

Hi friends this is text to speech in android:-

Layout is :-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#ffffff">
   
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Text To Speech"
    android:padding="15dip"
    android:textColor="#0587d9"
    android:textSize="26dip"
    android:gravity="center"
    android:textStyle="bold"/>

    <EditText android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Enter some text to speak"
        android:layout_marginTop="20dip"      
        android:layout_margin="10dip"/>
   
    <Button android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Speak Out"
        android:layout_margin="10dip"/>

</LinearLayout>








Class:-


public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */

private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tts = new TextToSpeech(this, this);

btnSpeak = (Button) findViewById(R.id.btnSpeak);

txtText = (EditText) findViewById(R.id.txtText);



btnSpeak.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
speakOut();
}

});
}

@Override
public void onDestroy() {
// Don't forget to shutdown!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}

@Override
public void onInit(int status) {
// TODO Auto-generated method stub

if (status == TextToSpeech.SUCCESS) {

int result = tts.setLanguage(Locale.US);


if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}

} else {
Log.e("TTS", "Initilization Failed");
}

}

private void speakOut() {

String text = txtText.getText().toString();

tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}


Thank you in advance:-


No comments:

Post a Comment