본문 바로가기
안드로이드 자바

[Android][JAVA] TextToSpeech를 사용해 텍스트(Text)를 음성으로 바꾸기

by teamnova 2023. 6. 26.

안녕하세요 !

이번 시간에는 사용자가 입력한 텍스트를 음성으로 전환시키는 방법에 대해 알아보겠습니다 !

 

먼저 레아이웃 파일입니다.

 

activity_tts.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".TTSActivity">

    <EditText
        android:id="@+id/speech_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="메시지를 입력하세요"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="55dp"
        android:lines="8"
        android:minLines="3"
        android:gravity="top|left"
        android:maxLength="10"
        android:padding="3dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="말하기"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"
        android:background="#E91E63"
        android:onClick="textSpeech"
        />

</LinearLayout>

텍스트를 입력할 수 있는 입력 칸과 텍스트를 음성으로 바꾼 후 들을 수 있게 해주는 버튼이 있습니다.

 

다음으로 자바 파일입니다.

 

TTSActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Locale;

public class TTSActivity extends AppCompatActivity implements TextToSpeech.OnInitListener{

    public static final int TTS_ENGINE_REQUEST = 101;

    private TextToSpeech textToSpeech;

    private EditText textForSpeech;

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

        textForSpeech = findViewById(R.id.speech_text);
    }

    //텍스트 -> 음성 전환
    public void textSpeech(View view) {

        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, TTS_ENGINE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == TTS_ENGINE_REQUEST && resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
        {
            //음성전환 준비
            textToSpeech = new TextToSpeech(this, this);
        }
        else { //데이터 다운로드
            Intent installIntent = new Intent();
            installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installIntent);
        }
    }

    @Override
    public void onInit(int status) {

        if(status == TextToSpeech.SUCCESS)//성공
        {
            int languageStatus = textToSpeech.setLanguage(Locale.KOREAN);

            //데이터 문제( 데이터가 없거나, 언어를 지원할 수 없다면
            if(languageStatus == TextToSpeech.LANG_MISSING_DATA || languageStatus == TextToSpeech.LANG_NOT_SUPPORTED)
            {
                Toast.makeText(this, "언어를 지원할 수 없습니다.", Toast.LENGTH_SHORT).show();
            }
            else { //데이터 성공
                String data = textForSpeech.getText().toString();

                int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);

                if(speechStatus == TextToSpeech.ERROR)
                {
                    Toast.makeText(this, "음성전환 에러입니다.", Toast.LENGTH_SHORT).show();
                }
            }
        }
        else { //실패
            Toast.makeText(this, "음성전환 엔진 에러입니다.", Toast.LENGTH_SHORT).show();
        }
    }
}

 

다음으로 실행화면 입니다.

 

 

보시다시피 입력한 텍스트를 음성으로 들을 수 있습니다.

오늘 준비한 내용은 여기까지 입니다.

감사합니다 !