Search This Blog

11 May 2010

Text-2-Speech

First we create a basic project:

F:\work> mvn archetype:generate -DarchetypeCatalog=http://kallisti.eoti.org:8081/content/repositories/snapshots/archetype-catalog.xml
choose the galatea-archetype plugin
groupId: org.eoti.android
artifactId: SpeechTest
version: 1.0-SNAPSHOT
F:\work> cd SpeechTest
F:\work\SpeechTest> mvn clean install

Now, let's modify our activity as per this tutorial...

Add this line to src\main\android\res\values\strings.xml:
    <string name="thanks">Thanks for listening to me speak.</string>
 Here's the code for the main activity [change to your class name as needed]:
public class SpeechTestActivity extends Activity implements TextToSpeech.OnInitListener {
    public static final int TTS_DATA_CHECK_CODE = 100;
    private TextToSpeech mTts;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Intent checkIntent = new Intent();
        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(checkIntent, TTS_DATA_CHECK_CODE);
    }

    protected void onActivityResult(
            int requestCode, int resultCode, Intent data) {
        if (requestCode == TTS_DATA_CHECK_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
                // success, create the TTS instance
                mTts = new TextToSpeech(this, this);
            } else {
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(
                    TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    }

    public void onInit(int status) {
        mTts.setLanguage(Locale.getDefault());
        mTts.speak(this.getString(R.string.hello), TextToSpeech.QUEUE_FLUSH, null);
        mTts.speak(this.getString(R.string.thanks), TextToSpeech.QUEUE_ADD, null);
    }

    @Override
    protected void onDestroy() {
        mTts.shutdown();
        super.onDestroy();
    }
}

Redeploy (mvn clean install) and you should hear it speak.

No comments:

Post a Comment