0

Text To Speech in Android

Trong bài học này mình sẽ giới thiệu cho các bạn về thư viện text to speech trong android hỗ trợ trong việc chuyển từ văn bản thành giọng nói. Tính năng này đặc biệt hữu ích khi lập trình các app về phát âm, từ điển…

Text to speech được đưa vào android từ API 21. Nên để lập trình với Text to speech chúng ta phải tạo project với API thấp nhất là 21.

Đầu tiên chúng ta tạo một project mới. Ở đây mình tạo một project là TextToSpeechExp với activity dạng empty activity và giới hạn API thấp nhất là 21.

Tiếp theo khi đã tạo xong project chúng ta xây dựng giao diện tại activity_main.xml gồm các RadioButton để tích chọn ngôn ngữ đọc từ văn bản. Một EditText để nhập văn bản cần đọc và một Button để bắt sự kiện đọc văn bản.

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.lethuy.texttospeechexp.MainActivity">

    <ImageView
        android:id="@+id/avtDevpro"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_framgia"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"/>

    <RadioGroup
        android:layout_alignRight="@+id/avtDevpro"
        android:layout_below="@+id/avtDevpro"
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_centerHorizontal="true">

        <RadioButton
            android:id="@+id/radio_en"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="English" />

        <RadioButton
            android:id="@+id/radio_fr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="false"
            android:text="France" />
    </RadioGroup>

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/radioGroup"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignRight="@+id/radioGroup"
        android:layout_below="@+id/radioGroup" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="58dp"
        android:text="Speak" />
</RelativeLayout>

Chuyển sang MainActivity.java ta code chức năng đọc văn bản.

Đầu tiên chúng ta gán ID cho các button, edittext trên activity_main.xml

private TextToSpeech textToSpeech;
    private EditText editText_text;
    private Button button;
    private RadioButton radio_en;
    private RadioButton radio_fr;
    RadioGroup radioGroup;

    private boolean ready;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText_text = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);
        radio_en = (RadioButton) findViewById(R.id.radio_en);
        radio_fr = (RadioButton) findViewById(R.id.radio_fr);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);

Đầu tiên chúng ta cần nhận diện ngôn ngữ để đọc văn bản khi tích chọn vào RadioButton. Ở đây chúng ta có 2 RadioButton để chọn 2 ngôn ngữ là ENGLIST và FRANCE. Hiện tại ở API 23 các địa phương sau được hỗ trợ:

  • en_US
  • de_DE
  • fr
  • es_ES
  • de
  • en
  • it_IT
  • it
  • en_GB
  • es
  • fr_FR
private Locale getUserSelectedLanguage() {
        int checkedRadioId = this.radioGroup.getCheckedRadioButtonId();
        if (checkedRadioId == R.id.radio_en) {
            return Locale.ENGLISH;
        } else if (checkedRadioId == R.id.radio_fr) {
            return Locale.FRANCE;
        }
        return null;
    }

Tiếp theo ta viết ra hàm kiểm tra các ngôn ngữ được hỗ trợ. Ta đặt một biến boolean là ready ở dạng toàn cục để kiểm tra và phân tích các trường hợp sảy ra khi chọn ngôn ngữ. Khi phát hiện ngôn ngữ được hỗ trợ thì boolean – true. Ngược lại các trường hợp khác là false. Và đưa ra các thông báo tương ứng

private boolean ready;

private void setTextToSpeechLanguage() {
        Locale language = this.getUserSelectedLanguage();
        if (language == null) {
            this.ready = false;
            Toast.makeText(this, "Not language selected", Toast.LENGTH_SHORT).show();
            return;
        }
        int result = textToSpeech.setLanguage(language);
        if (result == TextToSpeech.LANG_MISSING_DATA) {
            this.ready = false;
            Toast.makeText(this, "Missing language data", Toast.LENGTH_SHORT).show();
            return;
        } else if (result == TextToSpeech.LANG_NOT_SUPPORTED) {
            this.ready = false;
            Toast.makeText(this, "Language not supported", Toast.LENGTH_SHORT).show();
            return;
        } else {
            this.ready = true;
            Locale currentLanguage = textToSpeech.getVoice().getLocale();
            Toast.makeText(this, "Language " + currentLanguage, Toast.LENGTH_SHORT).show();
        }
    }

Tiếp theo ta khai báo biến TextToSpeech dạng toàn cục và gọi sự kiện kiểm tra ngôn ngữ setTextToSpeechLanguage() khi thay đổi lựa chọn ngôn ngữ trên RadioButton và gán sự kiện cho Button đọc văn bản

 textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                setTextToSpeechLanguage();

            }
        });
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                setTextToSpeechLanguage();
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speakOut();
            }
        });

speakOut là hàm chúng ta sẽ gọi để đọc văn bản.

private void speakOut() {
        if (!ready) {
            Toast.makeText(this, "Text to Speech not ready", Toast.LENGTH_LONG).show();
            return;
        }

        // Văn bản cần đọc.
        String toSpeak = editText_text.getText().toString();
        Toast.makeText(this, toSpeak, Toast.LENGTH_SHORT).show();
        String utteranceId = UUID.randomUUID().toString();
        textToSpeech.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
    }

Chúng ta Run app để kiểm tra kết quả. Nhớ rằng bạn phải run app ở máy ảo android 5.0 trở lên (API 21).

14114729_591583564348522_347232001_o.png

Chúc các bạn code vui vẻ!! ^_^


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí