Demo
MainActivity.java
package com.example.recyclerview;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private TextToSpeech tts;
private ImageButton ibSpeak;
private EditText etInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etInput = findViewById(R.id.et_input);
ibSpeak = findViewById(R.id.ib_speak);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.KOREA);
if(result == TextToSpeech.LANG_MISSING_DATA
||result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(getApplicationContext(), "this language is not supported", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "TTs Initialization failed", Toast.LENGTH_SHORT).show();
}
}
}
});
ibSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = etInput.getText().toString().trim();
int result = tts.speak(input, TextToSpeech.QUEUE_FLUSH, null);
if(result == TextToSpeech.ERROR) {
Toast.makeText(getApplicationContext(),"Error in converting Text to Speech", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(tts != null) {
tts.stop();
tts.shutdown();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<EditText
android:id="@+id/et_input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Try your text here"/>
<ImageButton
android:id="@+id/ib_speak"
android:layout_width="100dp"
android:layout_height="100dp"
app:srcCompat="@android:drawable/ic_btn_speak_now" />
</LinearLayout>
'Application Programming > Android' 카테고리의 다른 글
[Android/Java] 타이머 (0) | 2021.06.14 |
---|---|
[Android/Java] File stream 외부 Storage에 글 읽고 쓰기 (0) | 2021.06.14 |
[Android/Java] 음성인식 해서 글로 변환 (0) | 2021.06.14 |
[Android/Java] Sdcard에 이미지 다운로드 (0) | 2021.06.14 |
[Android/Java] Image download using AsyncTask (0) | 2021.06.14 |