반응형

2016. 11. 14 수정

김병희님이 댓글로 알려주셔서 onPause에 있는 코드를 onDestroy로 옮겼습니다.

다른 앱을 실행시키다 돌아왔을 때 음성 출력이 안되는 문제가 해결됩니다.




2015.12.03

입력창에 원하는 한글 문자열을 입력하고 버튼을 클릭하면 읽어주는 간단한 예제입니다. 생각보다 짧은 코드로 기능이 구현가능하네요..





activity_main.xml 파일입니다. 텍스트를 입력할 EditText 하나와 클릭하면 TTS를 실행시켜줄 버튼으로 구성되어 있습니다..

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
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:transitionGroup="true">
 
 
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:id="@+id/editText"/>
 
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text to Speech"
        android:id="@+id/button"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />
 
</RelativeLayout>
cs




MainActivity.java 파일입니다.


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package com.tistory.webnautes.texttospeech;
 
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
 
import android.speech.tts.TextToSpeech;
import android.view.View;
 
import android.widget.Button;
import android.widget.EditText;
 
import java.util.HashMap;
import java.util.Locale;
import android.widget.Toast;
 
 
public class MainActivity extends Activity {
    TextToSpeech tts;
    EditText inputtext;
    Button button;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        inputtext=(EditText)findViewById(R.id.editText);
        button=(Button)findViewById(R.id.button);
 
 
        tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    tts.setLanguage(Locale.KOREAN);
                }
            }
        });
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = inputtext.getText().toString();
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
 
 
                //http://stackoverflow.com/a/29777304
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ttsGreater21(text);
                } else {
                    ttsUnder20(text);
                }
 
            }
        });
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
 
        if(tts !=null){
            tts.stop();
            tts.shutdown();
        }
    }
 
 
    @SuppressWarnings("deprecation")
    private void ttsUnder20(String text) {
        HashMap<StringString> map = new HashMap<>();
        map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, map);
    }
 
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void ttsGreater21(String text) {
        String utteranceId=this.hashCode() + "";
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
    }
}
cs


문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts