본문 바로가기
자바(Java)/어플(앱) 만들기

안드로이드 - TTS (문자 소리내어읽기)

by 공.대.남 2020. 5. 11.
반응형

안녕하세요 공대남입니다.

이번시간에는 문자인 textview or editview 를 소리내어 읽어주는 안드로이드 어플을 만들까합니다.

읽기전 구독과 광고클릭 부탁드립니다! :)

 

먼저 xml 파일입니다.

Layout resource file

텍스트를 입력할 EditText, 클릭하면 음성 출력을 실행시킬 Button으로 구성

//activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">

<EditText
android:id="@+id/edt_speech"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="텍스트를 입력하세요."/>

<Button
android:id="@+id/btn_ent"
style="@style/Widget.AppCompat.Button.Borderless.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Speak"/>

</LinearLayout>

</android.support.constraint.ConstraintLayout>

 

 

 

java 파일입니다! 

TTS 생성 및 초기화

TTS를 생성하고 OnInitListener로 초기화

private Button btnEnter;
private EditText edtSpeech;

private TextToSpeech textToSpeech;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
//사용할 언어를 설정
int result = textToSpeech.setLanguage(Locale.KOREA);
//언어 데이터가 없거나 혹은 언어가 지원하지 않으면...
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(MainActivity.this, "이 언어는 지원하지 않습니다.", Toast.LENGTH_SHORT).show();
} else {
btnEnter.setEnabled(true);
//음성 톤
textToSpeech.setPitch(0.7f);
//읽는 속도
textToSpeech.setSpeechRate(1.2f);
}
}
}
});

edtSpeech = (EditText) findViewById(R.id.edt_speech);
btnEnter = (Button) findViewById(R.id.btn_ent);
btnEnter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Speech();

}
});
}

private void Speech() {
String text = edtSpeech.getText().toString();
// QUEUE_FLUSH: Queue 값을 초기화한 후 값을 넣는다.
// QUEUE_ADD: 현재 Queue에 값을 추가하는 옵션이다.
// API 21
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
// API 20
else
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);

}

// 메모리 누출을 방지하게 위해 TTS를 중지
@Override
protected void onStop() {
super.onStop();
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
}

728x90
반응형

댓글