2017-04-06 66 views
0

我一直在嘗試使用Google TTS引擎編寫語音輸出課程。 但是在互聯網上,我只能找到佈局和在MainActivity的onCreate和其他重寫方法中使用TTS服務的示例。Google Text To Speech作爲一個可以在需要時調用的Sperate類?

我想創建一個像sayThis(String someText)這樣的方法來說出傳遞的字符串。

+0

[這是一個簡單的例子](http://stackoverflow.com/questions/32936077/googles-text-to-speech-api-from-android-app#32936643)。 –

回答

1

你需要的是一個服務,這裏是我使用的一個:

import android.app.Service; 
    import android.content.Intent; 
    import android.os.IBinder; 
    import android.speech.tts.TextToSpeech; 
    import android.util.Log; 
    import java.util.Locale; 
    /** 
    * TextToSpeech Service 
    * 
    * Este servicio nos permite hacer uso del motor de TTS desde un servicio, es decir, invocándolo 
    * desde cualquier lugar. 
    * Antes de poder hacer uso del motor, el mismo debe estar inicializado (se tiene que haber llamado 
    * al metodo onInit, lo cual sucede automaticamente cuando se completa el proceso de inicializacion) 
    * 
    * Cada vez que se quiera usar, se debe iniciar este servicio con un intento, el cual debe traer 
    * como EXTRA el texto que se quiere reproducir. 
    */ 
    public class TTS_Service extends Service implements TextToSpeech.OnInitListener{ 
     private static final String TAG = "TTS_Service"; 
     public static final String EXTRA_TTS_TEXT = "com.package.EXTRA_TTS_TEXT"; 
     private String textToSpeak; 
     private static boolean initDone; 
     private TextToSpeech tts; 
     /* ON CREATE */ 
     /* ********* */ 
     @Override 
     public void onCreate() { 
      super.onCreate(); 
      initDone = false; 
      tts = new TextToSpeech(this,this/*OnInitListener*/); 
     } 
     /* ON INIT */ 
     /* ******* */ 
     @Override 
     public void onInit(int status) { 
      if (status == TextToSpeech.SUCCESS) { 
       tts.setLanguage(Locale.ENGLISH); 
       initDone = true; 
       Log.i(TAG, "TTS inicializado correctamente"); 
       speakOut(); 
      } else { 
       tts = null; 
       initDone = false; 
       Log.e(TAG, "Fallo al inicializar TTS"); 
      } 
     } 
     /* ON START COMAMND */ 
     /* **************** */ 
     @Override 
     public int onStartCommand(Intent intent, int flags, int startId) { 
      textToSpeak = "";        // Asumimos que no va a haber un texto 
      // Acoording to documentation, intent may be null if service is restarted 
      // so first we need to check if it is null before asking for extras 
      if ((null != intent) && (intent.hasExtra(EXTRA_TTS_TEXT))){ 
       textToSpeak = intent.getStringExtra(EXTRA_TTS_TEXT); 
      } 
      // Si ya se inicializo y hay un texto para reproducir, hazlo! 
      if (initDone) { 
       speakOut(); 
      } 
      // Debe ser stoppeado explicitamente 
      return START_STICKY; 
     } 
     /* ON DESTROY */ 
     /* ********** */ 
     @Override 
     public void onDestroy() { 
      // Shutdown TTS before destroying the Service 
      if (tts != null) { 
       tts.stop(); 
       tts.shutdown(); 
      } 
      super.onDestroy(); 
     } 
     /* ON BIND */ 
     /* ******* */ 
     @Override 
     public IBinder onBind(Intent arg0) { 
      return null; 
     } 
     /* SPEAK OUT */ 
     /* ********* */ 
     private void speakOut() { 
      // First need to check if textToSpeak is not null 
      if ((null != textToSpeak) && (!textToSpeak.equals(""))) { 
       if (null != tts) { 
        tts.setSpeechRate((float) 0.85);     // Set speech rate a bit slower than normal 
        tts.setLanguage(Locale.getDefault());    // Set deafualt Locale as Speech Languaje 
        //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
        // tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null, null); // Don't need and utteranceID to track 
        //} else { 
        tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null); 
        //} 
       } else { 
        Log.e(TAG, "No se puede hablar porque no existe TTS"); 
       } 
      }else{ 
       Log.w(TAG, "No hay texto para reproducir. Si se trata de la primer inicializacion, no pasa nada"); 
      } 
     } 
    } 

當喲想調用它,你就:

Intent tts_intent = new Intent(getApplicationContext(), com.package.TTS_Service.class); 
tts_intent.putExtra(TTS_Service.EXTRA_TTS_TEXT, texto_you_want); 
startService(tts_intent); 

希望它能幫助!

相關問題