Since I am trying to learn many programming languages, I created this simple Android app. What it does basically is taking a sentence phrase from an EditText ed and translate it to speech when you click the start button.
I used onActivityResult to prevent app from crashing when the EditText becomes empty.
I am sensing that this code, while working perfectly, is far from perfect.
import android.support.v7.app.AppCompatActivity;
import java.util.Locale;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements OnInitListener {
private TextToSpeech myTTS;
private EditText ed;
private String phrase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ed = findViewById(R.id.editText);
Button startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, 1);
phrase = ed.getText().toString();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
myTTS = new TextToSpeech(this, this);
myTTS.setLanguage(Locale.US);
} else {
// TTS data not yet loaded, try to install it
Intent ttsLoadIntent = new Intent();
ttsLoadIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(ttsLoadIntent);
}
}
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
myTTS.speak(phrase, TextToSpeech.QUEUE_FLUSH, null);
} else if (status == TextToSpeech.ERROR) {
myTTS.shutdown();
}
}
}