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

안드로이드에서 싱글톤(Singleton)으로 TTS(음성 출력) 사용하는 방법


본격적인 예제로 들어가기 전에, 싱글톤(singleton) 디자인 패턴이 무엇인지 간단히 짚고 넘어가겠습니다. 싱글톤은 하나의 클래스에 대해 인스턴스 생성을 단 하나로 제한하는 디자인 패턴입니다. 동시성(concurrency) 제어나, 애플리케이션 전체가 데이터 저장소에 접근할 수 있는 중앙 집중식 진입점을 만들 때 널리 활용됩니다.

이번 예제에서는 안드로이드에서 싱글톤 객체를 통해 TTS(Text To Speech, 음성 출력)를 사용하는 방법을 살펴보겠습니다.

1단계: 새 프로젝트 만들기

Android Studio에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력하여 프로젝트를 생성합니다.

2단계: 레이아웃 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <EditText
        android:id="@+id/editText"
        android:hint="Write here what to speak"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/show"
        android:text="TTS from singleTone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

위 코드에는 EditText와 버튼이 배치되어 있습니다. 사용자가 show 버튼을 클릭하면 EditText에 입력된 텍스트를 가져와 싱글톤 클래스를 통해 음성으로 출력합니다.

3단계: 메인 액티비티 구현

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.example.andy.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    Button show;
    singleTonExample singletonexample;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        show = findViewById(R.id.show);
        singletonexample = singleTonExample.getInstance();
        singletonexample.init(getApplicationContext());
        final EditText editText = findViewById(R.id.editText);
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!editText.getText().toString().isEmpty()) {
                    singletonexample.textToSpeach(editText.getText().toString());
                }
            }
        });
    }
}

위 코드에서는 singleTonExample을 싱글톤 클래스로 사용했습니다. 이제 singleTonExample.java 파일을 새로 생성하고 아래 코드를 추가합니다.

package com.example.andy.myapplication;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import java.util.Locale;

public class singleTonExample {
    static TextToSpeech t1;
    private static singleTonExample ourInstance = new singleTonExample();
    private Context appContext;

    private singleTonExample() { }

    public static Context get() {
        return getInstance().getContext();
    }

    public static synchronized singleTonExample getInstance() {
        return ourInstance;
    }

    public void init(Context context) {
        if (appContext == null) {
            this.appContext = context;
        }
    }

    private Context getContext() {
        return appContext;
    }

    public void textToSpeach(String Speak) {
        t1 = new TextToSpeech(get(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.UK);
                }
            }
        });
        t1.speak(Speak, TextToSpeech.QUEUE_FLUSH, null);
    }
}

싱글톤 클래스 내부에서는 TextToSpeech 객체를 초기화하고 언어를 영국 영어(Locale.UK)로 설정한 뒤, 전달받은 문자열을 QUEUE_FLUSH 방식으로 즉시 음성 출력합니다. 덕분에 액티비티 어디에서든 하나의 인스턴스를 통해 일관된 TTS 기능을 사용할 수 있습니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 기기 선택 목록에서 자신의 모바일 기기를 고르면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

안드로이드에서 싱글톤(Singleton)으로 TTS(음성 출력) 사용하는 방법

이제 화면의 버튼을 클릭하면 EditText에 입력한 텍스트가 싱글톤 클래스를 통해 음성으로 재생됩니다.