티스토리 뷰

국가 코드를 가져오는 법과 TTS 사용법을 포스팅하겠습니다.

다국어를 지원하는 앱을 개발하려면 사용중인 스마트폰이 어느 언어를 사용하는줄 알아야 하는데 

이것을 국가 코드를 얻어와서 해결할 수 있다.

그리고 TTS는 TextToSpeech의 줄임말로, 말 그대로 텍스트를 사람 목소리로 바꿔서 읽어주는 기능이다.

국가코드를 얻어서 TTS에 거기에 맞는 언어로 읽어줄수 있도록 하는 앱을 포스팅하겠다. 

1. 먼저 레이아웃 activity_main.xml 코드. 

<?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"/>

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+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/textview"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp" />

</RelativeLayout>

 

2. MAinActivity.java 

package com.jw.tts_example;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.TargetApi;
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 android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    TextToSpeech tts;
    EditText inputtext;
    TextView textView;
    Button button;


    Locale locale;

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

        inputtext=findViewById(R.id.editText);
        button= findViewById(R.id.button);
        textView= findViewById(R.id.textview);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            locale = getApplicationContext().getResources().getConfiguration().getLocales().get(0);
        }else{
            locale = getApplicationContext().getResources().getConfiguration().locale;
        }

        textView.setText("국가코드: " + locale.getCountry() + "   " + "언어코드: " + locale.getLanguage());




        tts=new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if(status != TextToSpeech.ERROR) {
                    switch (locale.getLanguage()){
                        case "ko": tts.setLanguage(Locale.KOREAN);
                        break;

                        case "en": tts.setLanguage(Locale.ENGLISH);
                        break;
                    }

                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = inputtext.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();
        }
    }


    @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=this.hashCode() + "";
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
    }
}

 

두번째 local.getCountry()는 국가 코드를 반환해준다.

나의 경우는 이 국가 코드를 이용해서 국가를 구분한다.

한국이라면 "KR"

미국이라면 "US"

일본이라면 "JP"

중국이라면 "CH"

대만이라면 "TW"

이렇게 각 나라별로 고유의 국가 코드를 반환해준다.

 

세번째 local.getLanguage()는 국가 언어 코드를 반환해준다.

한국은 "ko"

미국은 "en"

일본은 "ja"

중국은 "zh"

대만도 "zh"



 

댓글
최근에 달린 댓글
글 보관함
«   2024/05   »
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
Total
Today
Yesterday
    뽀로로친구에디
    최근에 올라온 글