Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 앱에서 TextToSpeech(TTS)로 텍스트를 음성으로 변환하는 방법

안드로이드 앱에서 TextToSpeech(TTS) 구현하기

TextToSpeech(TTS)는 안드로이드에서 기본으로 제공하는 API로, 입력된 텍스트를 실제 음성으로 변환하여 읽어 주는 기능입니다. 이 글에서는 사용자가 입력한 텍스트를 음성으로 출력하고, 피치(음조)속도까지 조절할 수 있는 간단한 TTS 앱을 만드는 과정을 단계별로 살펴보겠습니다.

완성된 앱의 동작 방식은 다음과 같습니다.

  • EditText에 원하는 텍스트를 입력합니다.
  • 시크바(SeekBar)를 이용해 음성의 피치와 재생 속도를 조절합니다.
  • '말하기' 버튼을 누르면 입력한 텍스트가 음성으로 출력됩니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택하여 새 프로젝트를 생성하고, 필요한 모든 정보를 입력합니다. 빈 액티비티(Empty Activity) 템플릿을 사용하면 이 예제를 그대로 따라 할 수 있습니다.

2단계 — 레이아웃 작성 (res/layout/activity_main.xml)

텍스트 입력창, 피치/속도 조절용 시크바, 말하기 버튼으로 구성된 세로 방향 LinearLayout 레이아웃을 아래와 같이 작성합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:hint="Enter Text" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pitch"
        android:textSize="16sp" />

    <SeekBar
        android:id="@+id/seekBarPitch"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:progress="50" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Speed"
        android:textSize="16sp" />

    <SeekBar
        android:id="@+id/seekBarSpeed"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:progress="50" />

    <Button
        android:id="@+id/btnSpeak"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:enabled="false"
        android:text="Say it!" />

</LinearLayout>

버튼은 초기 상태에서 enabled=false로 설정되어 있습니다. TTS 엔진 초기화가 성공적으로 완료된 후에만 활성화되도록 하기 위함입니다.

3단계 — 메인 액티비티 작성 (src/MainActivity.java)

TTS 엔진 초기화, 언어 설정, 버튼 클릭 시 음성 출력 처리를 담당하는 자바 코드입니다.

import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private TextToSpeech textToSpeech;
    private EditText editText;
    private SeekBar seekBarPitch;
    private SeekBar seekBarSpeed;
    private Button buttonSpeak;

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

        buttonSpeak = findViewById(R.id.btnSpeak);

        textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int result = textToSpeech.setLanguage(Locale.ENGLISH);
                    if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("TextToSpeech", "Language not supported");
                    } else {
                        buttonSpeak.setEnabled(true);
                    }
                } else {
                    Log.e("TextToSpeech", "Initialization failed");
                }
            }
        });

        editText = findViewById(R.id.editText);
        seekBarPitch = findViewById(R.id.seekBarPitch);
        seekBarSpeed = findViewById(R.id.seekBarSpeed);

        buttonSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speak();
            }
        });
    }

    private void speak() {
        String text = editText.getText().toString();
        float pitch = (float) seekBarPitch.getProgress() / 50;
        if (pitch < 0.1) pitch = 0.1f;
        float speed = (float) seekBarSpeed.getProgress() / 50;
        if (speed < 0.1) speed = 0.1f;

        textToSpeech.setPitch(pitch);
        textToSpeech.setSpeechRate(speed);
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    @Override
    protected void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
}

코드 핵심 포인트

  • OnInitListener: TTS 엔진 초기화 결과를 콜백으로 받습니다. 초기화에 성공하면 언어를 영어(Locale.ENGLISH)로 설정하고, 실패하면 로그를 남깁니다.
  • speak(): 시크바 값(0~100)을 50으로 나눠 피치와 속도(0.0~2.0 범위)를 계산합니다. 최소값 0.1 미만은 0.1로 보정해 오류를 방지합니다.
  • QUEUE_FLUSH: 새 음성 출력 요청 시 기존 대기열을 비우고 즉시 재생합니다.
  • onDestroy(): 액티비티 종료 시 stop()shutdown()을 호출해 TTS 리소스를 해제합니다. 메모리 누수를 방지하는 중요한 습관입니다.

💡 한국어 음성을 사용하려면 Locale.ENGLISH 대신 Locale.KOREAN을 사용하세요. 단, 기기에 한국어 TTS 데이터가 설치되어 있어야 정상 동작합니다.

4단계 — 매니페스트 확인 (AndroidManifest.xml)

매니페스트 파일에는 별도의 권한 선언 없이 MainActivity만 등록하면 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

앱 실행 및 테스트

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 스마트폰을 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일을 열고 툴바의 Run(실행) 아이콘을 클릭한 뒤, 목록에서 연결된 모바일 기기를 선택하세요. 앱이 설치되어 실행되면 다음과 같은 기본 화면이 표시됩니다.

안드로이드 앱에서 TextToSpeech(TTS)로 텍스트를 음성으로 변환하는 방법

텍스트를 입력하고 피치와 속도를 조절한 후 'Say it!' 버튼을 누르면, 설정한 음조와 속도로 텍스트가 음성으로 출력되는 것을 확인할 수 있습니다.