Rabu, 15 Mei 2013

Membuat Aplikasi Teks Berbicara pada Android (Text To Speech / TTS) Teks ke Suara

Setelah berhasil membuat Aplikasi Speech to Teks Inggris di Android, rasanya sangat tidak lengkap jika kita tidak membuat sebaliknya yaitu  Aplikasi Android Text to Speech (Teks ke Suara). Seperti biasa, buka Eclipse, buat project Android baru.

Buat MainActivity.java sehingga berisi kode program berikut :








package com.example.texttospeechinggris;

import java.util.Locale;

import android.os.Bundle;
import android.app.Activity;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
//http://cariprogram.blogspot.com
// nuramijaya@gmail.com
public class MainActivity extends Activity implements OnInitListener {
TextToSpeech TTS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        TTS = new TextToSpeech(MainActivity.this, MainActivity.this);
        
        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText editText1 = (EditText)findViewById(R.id.editText1);
TTS.speak(editText1.getText().toString(), TextToSpeech.QUEUE_ADD, null);
}
});
        
        Button button2 = (Button)findViewById(R.id.button2);
        button2.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
EditText editText1 = (EditText)findViewById(R.id.editText1);
TTS.speak(editText1.getText().toString(), TextToSpeech.QUEUE_FLUSH, null);
}
});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

@Override
public void onInit(int arg0) {
// TODO Auto-generated method stub
//TTS.setLanguage(Locale.ENGLISH);
//BAHASA INDONESIA TDK ADA :(
}

/*
// CARA MENGECEK APAKAH TTS DISUPPORT DAN MEMANGGIL INSTALLER TTS GOOGLE PLAY
 
   //find out whether speech recognition is supported
        PackageManager packManager = getPackageManager();
        List<ResolveInfo> intActivities = packManager.queryIntentActivities
        (new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (intActivities.size() != 0) {
        //speech recognition is supported - detect user button clicks
            speechBtn.setOnClickListener(this);
            //prepare the TTS to repeat chosen words
            Intent checkTTSIntent = new Intent();  
            //check TTS data  
            checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);  
            //start the checking Intent - will retrieve result in onActivityResult
            startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE); 
        }
        else 
        {
        //speech recognition not supported, disable button and output message
            speechBtn.setEnabled(false);
            Toast.makeText(this, "Oops - Speech recognition not supported!", Toast.LENGTH_LONG).show();
        }
        
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //check speech recognition result 
        if (requestCode == VR_REQUEST && resultCode == RESULT_OK) 
        {
        //store the returned word list as an ArrayList
            ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            //set the retrieved list to display in the ListView using an ArrayAdapter
            wordList.setAdapter(new ArrayAdapter<String> (this, R.layout.word, suggestedWords));
        }
        
        //returned from TTS data check
        if (requestCode == MY_DATA_CHECK_CODE) 
        {  
       //we have the data - create a TTS instance
       if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)  
        repeatTTS = new TextToSpeech(this, this);  
       //data not installed, prompt the user to install it  
       else 
       {  
        //intent will take user to TTS download page in Google Play
        Intent installTTSIntent = new Intent();  
        installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);  
        startActivity(installTTSIntent);  
       }  
        }

        //call superclass method
        super.onActivityResult(requestCode, resultCode, data);
    }

*/
    
}


Kemudian layout activity_main.xml isikan layout seperti ini :


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text To Speech English" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text To Speech (ADD)" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Text To Speech (FLUSH)" />

</LinearLayout>


Terakhir konfigurasi di AndroidManifest.xml tidak perlu kita rubah :


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.texttospeechinggris"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.texttospeechinggris.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


Hasilnya :


Apabila kita ketikkan suatu Kata atau Kalimat, kemudian klik Tombol Text To Speech maka akan keluar suara yang membacakan Teks tersebut.

Project selengkapnya dapat didownload disini. Jika kesulitan coba baca cara mendownloadnya berikut ini.

Semoga bermanfaat.

1 komentar:

  1. makasih infonya gan..
    ijin sedot.. hehe..

    gan, TTS yg bahasa indonesia ada ga gan..

    BalasHapus