Page 163 - The Definitive Guide to Building Java Robots
P. 163
Preston_5564C05.fm Page 144 Tuesday, September 20, 2005 5:13 AM
144 CHAPTER 5 ■ SPEECH
Code Objective
Create an interface that standardizes behavior between three implementing speech synthesis
classes.
Code Discussion
Our interface has only three methods. The first, open, gets the system ready for voice processing.
The second, speak, takes a string input and contains the implementation for speaking. It
throws an exception if there’s a problem. Finally, there’s close, which shuts down the voice
processing. See Example 5-4.
Example 5-4. Voice.java
package com.scottpreston.javarobot.chapter5;
public interface JVoice {
// opens or allocates voice engine
public void open();
// speaks
public void speak(String words) throws Exception;
// closes or deallocates voice engine
public void close();
}
Code Objective
The code objective here is to create a speech synthesis implementation using JSAPI 1.0.
Code Discussion
The class that does all of our work for the Java Speech API is the java.speech.synthesis.
Synthesizer class. To use this class, we need to create a new Synthesizer via the Central.
createSynthesizer() method. This allows us to create any type of synthesizer we like with the
constructor being a SynthesizerModeDesc class. After construction, the other methods follow
our interface defined in Example 5-4.
The method open() calls the allocate() method on the Synthesizer. The close() method
calls deallocate() on the Synthesizer.
The speak() method does three things. First, it calls resume() on the Synthesizer because
it’s recently allocated and needs to change its state to RESUMED so it can begin processing text
to speech. Second, we call speakPlainText because we want to ignore Java Speech Markup
Language (JSML). Third, we call waitEngineState() because we want to wait until the engine has
placed itself in the QUEUE_EMPTY state. It does this when it’s done talking. See Example 5-5.