package tts.ttsdemo;

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.*;
import android.widget.*;
import android.os.Build;

public class MainActivity extends Activity 
					implements View.OnClickListener, OnInitListener
{
    ImageButton ttsButton;
    TextView msg;
    EditText editText1;
    TextToSpeech tts;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ttsButton = (ImageButton) findViewById(R.id.ttsButton);
        editText1 = (EditText) findViewById(R.id.editText1);
        msg = (TextView) findViewById(R.id.msg);
        ttsButton.setOnClickListener ( this );
        tts = new TextToSpeech(this, this);
    }
    
    public void onClick(View view) {
    	speak();
    }

	@Override
	public void onInit(int state) {
		// TODO Auto-generated method stub
	    if (state == TextToSpeech.SUCCESS) {
            msg.setText("TTS initialized successfully!\n " +
            		"Enter a sentence and click TTS.");
            int result = tts.setLanguage(Locale.US);
 
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                msg.setText("TTS: Language not supported!");
            } else {
                ttsButton.setEnabled(true);
                speak();
            }
 
        } else {
            msg.setText("TTS: Initilization Failed!");
        }		
	}
	
    private void speak() {    	 
        String text = editText1.getText().toString();
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
    
    @Override
    public void onDestroy() {
        // Don't forget to shutdown tts!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
}
