티스토리 뷰
구글 STT (Speech-to-Text)
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is TextView Result"
android:textSize="26dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="start speech"
android:textSize="18dp"
app:layout_constraintTop_toBottomOf="@+id/tvResult"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintVertical_bias="0.1"/>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
package com.jwsoft.kotlinproject
import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var speechRecognizer: SpeechRecognizer
private lateinit var recognitionListener: RecognitionListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
requestPermission()
var intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, packageName)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR")
setListener()
btnStart.setOnClickListener {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
speechRecognizer.setRecognitionListener(recognitionListener)
speechRecognizer.startListening(intent)
}
}
private fun requestPermission() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
// 거부해도 계속 노출됨. ("다시 묻지 않음" 체크 시 노출 안됨.)
// 허용은 한 번만 승인되면 그 다음부터 자동으로 허용됨.
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.RECORD_AUDIO), 0)
}
}
private fun setListener() {
recognitionListener = object: RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {
Toast.makeText(applicationContext, "음성인식을 시작합니다.", Toast.LENGTH_SHORT).show()
}
override fun onBeginningOfSpeech() {
}
override fun onRmsChanged(rmsdB: Float) {
}
override fun onBufferReceived(buffer: ByteArray?) {
}
override fun onEndOfSpeech() {
}
override fun onError(error: Int) {
var message: String
when (error) {
SpeechRecognizer.ERROR_AUDIO ->
message = "오디오 에러"
SpeechRecognizer.ERROR_CLIENT ->
message = "클라이언트 에러"
SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS ->
message = "퍼미션 없음"
SpeechRecognizer.ERROR_NETWORK ->
message = "네트워크 에러"
SpeechRecognizer.ERROR_NETWORK_TIMEOUT ->
message = "네트워크 타임아웃"
SpeechRecognizer.ERROR_NO_MATCH ->
message = "찾을 수 없음"
SpeechRecognizer.ERROR_RECOGNIZER_BUSY ->
message = "RECOGNIZER가 바쁨"
SpeechRecognizer.ERROR_SERVER ->
message = "서버가 이상함"
SpeechRecognizer.ERROR_SPEECH_TIMEOUT ->
message = "말하는 시간초과"
else ->
message = "알 수 없는 오류"
}
Toast.makeText(applicationContext, "에러 발생 $message", Toast.LENGTH_SHORT).show()
}
override fun onResults(results: Bundle?) {
var matches: ArrayList<String> = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) as ArrayList<String>
for (i in 0 until matches.size) {
tvResult.text = matches[i]
}
}
override fun onPartialResults(partialResults: Bundle?) {
}
override fun onEvent(eventType: Int, params: Bundle?) {
}
}
}
}
실행 후 버튼 클릭 후 말하면 텍스트 뷰에 반영됨.
성능은 좋지 않음.
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] lateinit vs Delegates.notNull<>() (0) | 2020.08.27 |
---|---|
[Kotlin] InputMethodManager (0) | 2020.08.25 |
[Kotlin] ArrayList.removeAt() (0) | 2020.08.20 |
[Kotlin] String.replace() (0) | 2020.08.20 |
[Kotlin] for each (0) | 2020.08.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 코틀린
- Livedata
- DataBinding
- ViewModel
- 안드로이드
- fragment
- ViewPager2
- James Kim
- Android
- recyclerview
- coroutine
- handler
- Vue.js #Vue.js + javascript
- Kotlin
- activity
- MVVM
- Design Pattern
- JSONObject
- XML
- 안드로이드 #코틀린 #Android #Kotlin
- java
- View
- Architecture Pattern
- TabLayout
- 혀가 길지 않은 개발자
- Intent
- 자바
- JSONArray
- ArrayList
- CoordinatorLayout
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
글 보관함