안드로이드 개발

글자를 음성으로 재생하는 안드로이드 앱 개발 text to speech tts

피커 2022. 12. 27. 16:27
728x90
반응형

문자를 음성으로 변경해서 재생하는것을 TTS (Text To Speech)라고 합니다.

안드로이드 앱에서는 해당 기능을 기본  API로 지원하고 있어 소개합니다.

 

1. TTS?

  -. Text To Speech의 줄임말입니다.

 

2. TTS API 사용법

   2.1 영상 (youtube)

       -. https://youtu.be/UIUiPqyknvQ

    2.2 코드 (Github)

       -. https://github.com/pickersoft/texttospeech

 

GitHub - PickerSoft/texttospeech

Contribute to PickerSoft/texttospeech development by creating an account on GitHub.

github.com

 

3. API 사용 방법

  3.1 Layout XML

     

<EditText
    android:id="@+id/input"
    android:layout_width="0dp"
    android:layout_height="50dp"
    android:layout_marginBottom="150dp"
    android:textAlignment="center"
    android:text="Hi. My name is picker. Nice to meet you."
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    />

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_baseline_record_voice_over_24"
    android:layout_marginTop="100dp"
    android:onClick="onSpeech"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"/>

3.2 MainActivity.kt

class MainActivity : AppCompatActivity() {
    lateinit var mtts:TextToSpeech
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mtts = TextToSpeech(this) {
            mtts.language = Locale.ENGLISH
        }
    }

    fun onSpeech(view: View) {
        val tv = findViewById<TextView>(R.id.input)
        mtts.speak(tv.text, TextToSpeech.QUEUE_FLUSH, null, null)
    }
}

 3.3 Demo

4. TTS API DOC 

TTS API 문서
Synthesizes speech from text for immediate playback or to create a sound file.
A TextToSpeech instance can only be used to synthesize text once it has completed its initialization.
Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization.
When you are done using the TextToSpeech instance,
call the shutdown() method to release the native resources used by the TextToSpeech engine.
Apps targeting Android 11 that use text-to-speech should declare TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE in the queries elements of their manifest:

 

반응형