TTS (Text To Speech)


참고
http://webnautes.tistory.com/847
http://sharp57dev.tistory.com/27



1) 메인 엑티비티에 아래와 같이 기술합니다.
    private TextToSpeech tts;
    private EditText editText;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != ERROR) {
                    tts.setLanguage(Locale.KOREAN); // 언어
                    tts.setPitch(1.0f);             // 음성 톤
                    tts.setSpeechRate(1.0f);        // 읽는 속도
                }
            }
        });

        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = editText.getText().toString();
                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();
            tts = null;
        }
    }

    @SuppressWarnings("deprecation")
    private void ttsUnder20(String text) {
        HashMap<string, string> 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 = String.valueOf(this.hashCode());
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
    }
MainActivity.java



2) Layout 파일은 EditText, Button을 가지는 간단한 코드이므로 생략합니다.


'개발 > Android' 카테고리의 다른 글

TTS (Text To Speech)  (0) 2018.01.11

+ Recent posts