2012-08-24 20 views

回答

0

創建App類和TextToSpeech一個實例中它:

public class App extends Application { 
    private static TextToSpeech mTts; 

    public static TextToSpeech getmTts() { 
     return mTts; 
    } 

    public void onCreate() { 
     super.onCreate(); 

     // creating TTS: 
     mTts = new TextToSpeech(this, this); 
     mTts.setLanguage(Locale.US); 
     mTts.stop(); 
    } 
}  

聲明App(上文)在您的清單:

<application 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:name="your.application.package.App" > 

您的服務,當你想發送broadcastBroadcastReceiver例如這樣的:

public class TTSReceiver extends BroadcastReceiver implements OnInitListener { 

    private TextToSpeech mTts; 
    private String message; 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     mTts = App.getmTts(); 
     mTts.setLanguage(Locale.US); 
     message = "your message"; 
     mTts.stop(); 
     mTts.speak(message, TextToSpeech.QUEUE_FLUSH, null); 
    } 

    public void onInit(int status) { 
    } 

} 
0
public class SpeakService extends Service implements OnInitListener { 

    public static TextToSpeech tts; 
    private String string; 

    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     tts = new TextToSpeech(this, this); 
     super.onCreate(); 
    } 

    @Override 
    public void onDestroy() { 
     if (tts != null) { 
      tts.stop(); 
      tts.shutdown(); 
     } 
     super.onDestroy(); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     string = intent.getStringExtra("string"); 
    } 

    @Override 
    public void onInit(int status) { 
     if (status == TextToSpeech.SUCCESS) { 
     int result = tts.setLanguage(Locale.UK); 
     if (result == TextToSpeech.LANG_MISSING_DATA 
       || result == TextToSpeech.LANG_NOT_SUPPORTED) { 
      Log.d("SpeakService", "Language is not available."); 
     } else { 
      if (!TextUtils.isEmpty(string)) { 
       speak(string); 
      } else { 

       speak("Error"); 
      } 
     } 
     } else { 
     Log.d("SpeakService", "Could not initialize TextToSpeech."); 
    } 
    } 

    private void speak(String string) { 
     tts.speak(string, TextToSpeech.QUEUE_FLUSH, null); 
    }