티스토리 뷰
구글 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="150dp"
android:layout_height="60dp"
android:textAllCaps="false"
android:text="start speech"
android:textSize="20dp"
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.java
package com.jwsoft.javaproject;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private SpeechRecognizer speechRecognizer;
private RecognitionListener recognitionListener;
TextView tvResult;
Button btnStart;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResult = findViewById(R.id.tvResult);
btnStart = findViewById(R.id.btnStart);
requestPermission();
setListener();
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ko-KR");
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplicationContext());
speechRecognizer.setRecognitionListener(recognitionListener);
speechRecognizer.startListening(intent);
}
});
}
private void requestPermission() {
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
// 거부해도 계속 노출됨. ("다시 묻지 않음" 체크 시 노출 안됨.)
// 허용은 한 번만 승인되면 그 다음부터 자동으로 허용됨.
ActivityCompat.requestPermissions(this,
new String[] {Manifest.permission.RECORD_AUDIO}, 0);
}
}
private void setListener() {
recognitionListener = new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle params) {
Toast.makeText(getApplicationContext(), "음성인식 시작", Toast.LENGTH_SHORT).show();
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
}
@Override
public void onError(int error) {
String message;
switch (error) {
case SpeechRecognizer.ERROR_AUDIO:
message = "오디오 에러";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "클라이언트 에러";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "퍼미션 에러";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "네트워크 에러";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "네트워크 타임아웃";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "찾을 수 없음";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "인식 시도 중";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "서버가 이상함";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "말하는 시간 초과";
break;
default:
message = "알 수 없는 에러";
break;
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
@Override
public void onResults(Bundle results) {
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i=0; i<matches.size(); i++) {
tvResult.setText(matches.get(i));
}
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
};
}
}
실행 후 버튼 클릭 후 말하면 텍스트 뷰에 반영됨.
성능은 좋지 않음.
'Android > Java' 카테고리의 다른 글
[Java] Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK (0) | 2020.09.02 |
---|---|
[Java] InputMethodManager (0) | 2020.08.25 |
[Java] ArrayList.remove() (0) | 2020.08.20 |
[Java] String.replace() (0) | 2020.08.20 |
[Java] for each (0) | 2020.08.20 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- TabLayout
- JSONArray
- 안드로이드
- JSONObject
- MVVM
- coroutine
- fragment
- Vue.js #Vue.js + javascript
- Kotlin
- View
- 자바
- Architecture Pattern
- ViewModel
- James Kim
- activity
- CoordinatorLayout
- DataBinding
- 코틀린
- 혀가 길지 않은 개발자
- Design Pattern
- ArrayList
- recyclerview
- Livedata
- Android
- handler
- XML
- java
- ViewPager2
- 안드로이드 #코틀린 #Android #Kotlin
- Intent
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
글 보관함