본문 바로가기
안드로이드 코틀린

[Kotlin][Android] SST(SpeechToText) 기능 구현하기

by teamnova 2021. 5. 31.

안녕하세요 ~ 

 

오늘은 SST 기능을 구현해 보겠습니다. 

 

SpeehToText(이하 SST) 기능은 음성을 인식해서 텍스트로 변환시켜주는 기능입니다.

 

한번 만들어 볼까요?

 

 

스틱 코드?

stickode.com/mainlogin.html

 

STICKODE

 

stickode.com


 

권한 설정

Manifest에 권한을 설정해줍니다.

 

AndroidManifest.xml

 

        // MainActivity.kt
        
        // 권한 체크 코드
        if (Build.VERSION.SDK_INT >= 23)
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.INTERNET, Manifest.permission.RECORD_AUDIO), REQUEST_CODE)

 

 


 

 

레이아웃 만들기

 

activity_main.xml

 

인식한 음성을 텍스트로 보여주는 뷰와 SST를 동작시키기 위한 버튼을 하나 만들어 주겠습니다.

아래는 전체 레이아웃 소스입니다.

 

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">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textSize="25sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/STTButton"
        android:layout_width="50sp"
        android:layout_height="50sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        android:background="?selectableItemBackground"
        app:srcCompat="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="[ 인식한 텍스트 ]"
        android:textSize="20sp"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.8" />

</android.support.constraint.ConstraintLayout>

 

 


 

 

SST 기능 구현

 

MainActivity.kt

 

앞에서 만들어준 마이크 이미지의 버튼을 눌렀을 때, SST 기능이 동작하도록 스틱 코드를 이용해서 기능을 추가해 보도록 하겠습니다.

 

스틱코드에 등록되있는 SST 코드 사용

/***
*  SpeechToText 설정 및 동작
*/
    private  fun startSTT() {
        val speechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
            putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, packageName)
            putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
        }

        speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this).apply {
            setRecognitionListener(recognitionListener())
            startListening(speechRecognizerIntent)
        }

    }
/***
*  SpeechToText 기능 세팅
*/
    private fun recognitionListener() = object : RecognitionListener {

        override fun onReadyForSpeech(params: Bundle?) = Toast.makeText(this@MainActivity, "음성인식 시작", Toast.LENGTH_SHORT).show()

        override fun onRmsChanged(rmsdB: Float) {}

        override fun onBufferReceived(buffer: ByteArray?) {}

        override fun onPartialResults(partialResults: Bundle?) {}

        override fun onEvent(eventType: Int, params: Bundle?) {}

        override fun onBeginningOfSpeech() {}

        override fun onEndOfSpeech() {}

        override fun onError(error: Int) {
            when(error) {
                SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> Toast.makeText(this@MainActivity, "퍼미션 없음", Toast.LENGTH_SHORT).show()
            }
        }

        override fun onResults(results: Bundle) {
            Toast.makeText(this@MainActivity, "음성인식 종료", Toast.LENGTH_SHORT).show()
            textView.text = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)!![0]
        }
    }

 

이제 아까 만들어놨던 버튼 리스너에 위에서 만들어준 SST 기능을 연결시켜줍니다.

 

 

이제 마이크 이미지의 버튼을 누르면 SST 기능이 동작하도록 세팅이 끝났습니다.  마지막으로 잘 동작하는지 테스트해보도록 하겠습니다.

 

 


 

 

테스트

 

완성!

 

정상적으로 잘 동작하는 걸 확인할 수 있었습니다 : )