Page 168 - The Definitive Guide to Building Java Robots
P. 168

Preston_5564C05.fm  Page 149  Tuesday, September 20, 2005  5:13 AM



                                                                                  CHAPTER 5  ■  SPEECH   149



                        Example 5-9. MicrosoftVoice.java
                        package com.scottpreston.javarobot.chapter5;

                        public class MicrosoftVoice implements JVoice {

                            // worker class for voice
                            private QuadmoreTTS voice;
                            // private instance to ensure only one is active
                            private static MicrosoftVoice instance;

                            // private constructor prevents initialization
                            // called by getInstance
                            private MicrosoftVoice() {
                                voice = new QuadmoreTTS();
                            }

                            // static methods ensure one instance per class
                            public static MicrosoftVoice getInstance() throws Exception {
                                if (instance == null) {
                                    // returns self
                                    instance = new MicrosoftVoice();
                                }
                                return instance;
                            }

                            public void open() {
                                // do nothing
                            }

                            public void close() {
                                // do nothing
                            }

                            //speak, otherwise throw exception
                            public void speak(String s) throws Exception {
                                if (!voice.SpeakDarling(s)) {
                                    throw new Exception("Unable to speak");
                                }
                            }

                            // sample usage
                            public static void main(String args[]) {
                                try {
                                    MicrosoftVoice v = MicrosoftVoice.getInstance();
                                    v.speak("Java Robots Are Cool!");
   163   164   165   166   167   168   169   170   171   172   173