
public class TTSSTT extends AppCompatActivity implements TextToSpeech.OnInitListener {
EditText edit;
Button button;
TextView txtSpeechInput;
ImageButton btnSpeak;
private TextToSpeech myTTS;
private final int REQ_CODE_SPEECH_INPUT = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ttsstt);
setTitle("TTS/STT");
myTTS=new TextToSpeech(getApplicationContext(),this);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.button);
txtSpeechInput=(TextView)findViewById(R.id.txtSpeechInput);
btnSpeak=(ImageButton)findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
promptSpeechInput();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String str=txtSpeechInput.getText().toString();
myTTS.speak(str,TextToSpeech.QUEUE_FLUSH,null);
}
});
}
@Override
public void onInit(int i) {
}
private void promptSpeechInput(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//사용자의 음성 입력을 받아서 동일한 활동으로 반환
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
edit.setText(result.get(0));
}
break;
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}