Moblie/Android
androidStudio/java/TTS 사용하기
zyin
2021. 11. 30. 13:41
코드 작성하기
1. manifests에 action추가
<manifest>...
<queries>
<intent>
<action android:name="android.intent.action.TTS_SERVICE"/>
</intent>
</queries>
<application .../>
</manifest>
2. xml에 버튼 추가
<ImageButton
android:id="@+id/imageButton_speak"
android:layout_width="30dp"
android:layout_height="30dp"
app:layout_constraintEnd_toStartOf="@+id/memu" />
3. code 추가
import static android.speech.tts.TextToSpeech.ERROR;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
ImageButton bt_qrcode;
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_qrcode = findViewById(R.id.main_ImageButton_qrcode);
bt_qrcode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
speak("테스트");
}
});
}
private void speak(String text) {
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != ERROR){
int result = tts.setLanguage(Locale.KOREA); // 언어 선택
if(result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA){
Log.e("TTS", "This Language is not supported");
}else{
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
}else{
Log.e("TTS", "Initialization Failed!");
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if(tts!=null){ // 사용한 TTS객체 제거
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
4. 오류
다른 블로그를 참고하여 작성하다가 texttospeech: speak failed: not bound to tts engine 오류가 났다. TTS가 완전히 초기화되기 전에 tts를 사용했기 때문이라고 했다. tts를 사용할 때마다 새롭게 생성하도록 해서 문제를 해결했다.
// 실패한 코드
private void speak(String text) {
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status != ERROR){
int result = tts.setLanguage(Locale.KOREA); // 언어 선택
if(result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA){
Log.e("TTS", "This Language is not supported");
}
}else{
Log.e("TTS", "Initialization Failed!");
}
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
}
});
}
manifests에 action추가하지 않았더니, state 변수에 ERROR 값이 저장되었다. 1번처럼 작성 후 제대로 작동했다.
결과
참고자료
https://developer.android.com/reference/android/speech/tts/TextToSpeech
TextToSpeech | Android Developers
developer.android.com