Created
June 3, 2019 00:01
-
-
Save ardovic/d3f42cc4c6fea59c99382dd5ff1b1185 to your computer and use it in GitHub Desktop.
Sample Text to Speech implementation (Android Activity)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.content.Intent; | |
| import android.speech.tts.TextToSpeech; | |
| import android.support.v7.app.AppCompatActivity; | |
| import android.os.Bundle; | |
| import android.view.View; | |
| import android.widget.Button; | |
| import android.widget.EditText; | |
| import android.widget.Toast; | |
| public class SampleTextToSpeechActivity extends AppCompatActivity implements TextToSpeech.OnInitListener { | |
| int MY_DATA_CHECK_CODE = 1000; | |
| TextToSpeech textToSpeech; | |
| EditText editText; | |
| Button button; | |
| @Override | |
| protected void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| setContentView(R.layout.activity_main); | |
| editText = (EditText) findViewById(R.id.editText); | |
| button = (Button) findViewById(R.id.button); | |
| button.setOnClickListener(new View.OnClickListener() { | |
| @Override | |
| public void onClick(View view) { | |
| String text = editText.getText().toString(); | |
| if (text.length() > 0) { | |
| textToSpeech.speak(text, TextToSpeech.QUEUE_ADD, null); | |
| } | |
| } | |
| }); | |
| Intent intent = new Intent(); | |
| intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); | |
| startActivityForResult(intent, MY_DATA_CHECK_CODE); | |
| } | |
| @Override | |
| protected void onActivityResult(int requestCode, int resultCode, Intent data) { | |
| if(requestCode == MY_DATA_CHECK_CODE) { | |
| if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { | |
| textToSpeech = new TextToSpeech(this, this); | |
| } else { | |
| Intent intent = new Intent(); | |
| intent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); | |
| startActivity(intent); | |
| } | |
| } | |
| } | |
| @Override | |
| public void onInit(int i) { | |
| if(i == TextToSpeech.SUCCESS) { | |
| Toast.makeText(this, "Operation successful!", Toast.LENGTH_SHORT).show(); | |
| } else if(i == TextToSpeech.ERROR) { | |
| Toast.makeText(this, "Error reading text!", Toast.LENGTH_SHORT).show(); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment