2012-07-10 3 views
7

Estoy desarrollando una aplicación de Android en la que estoy usando la conversión de texto a voz. Lo que necesito cuando abro la aplicación es la conversión de texto a voz. Después de la terminación de este quiero hacer algo de código thing.My pareceNo se puede detectar la finalización de TTS (devolución de llamada) android.

public class Mainactivity extends Activity implements OnInitListener, OnUtteranceCompletedListener{ 
    private static int REQ_CODE = 1; 
    private TextToSpeech tts = null; 
    private boolean ttsIsInit = false; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    startTextToSpeech(); 
    } 

    private void startTextToSpeech() { 
     Intent intent = new Intent(Engine.ACTION_CHECK_TTS_DATA); 
     startActivityForResult(intent, REQ_CODE); 
    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (requestCode == REQ_CODE) { 
      if (resultCode == Engine.CHECK_VOICE_DATA_PASS) { 
       tts = new TextToSpeech(this, this); 
      } 
      else { 
       Intent installVoice = new Intent(Engine.ACTION_INSTALL_TTS_DATA); 
       startActivity(installVoice); 
      } 
     } 
    } 

     public void onInit(int status) { 
      if (status == TextToSpeech.SUCCESS) { 
       ttsIsInit = true; 
       int result = tts.setOnUtteranceCompletedListener(this); 
       if (tts.isLanguageAvailable(Locale.ENGLISH) >= 0) 
        tts.setLanguage(Locale.ENGLISH); 
       tts.setPitch(5.0f); 
       tts.setSpeechRate(1.0f); 

       HashMap<String, String> myHashAlarm = new HashMap<String, String>(); 
        myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_ALARM)); 
        myHashAlarm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "SOME MESSAGE"); 
        tts.speak("hi how are you?", TextToSpeech.QUEUE_FLUSH, myHashAlarm); 
      } 
     } 

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

    @Override 
    public void onUtteranceCompleted(String uttId) { 
     Toast.makeText(Mainactivity.this,"done", Toast.LENGTH_LONG).show(); 
     if (uttId.equalsIgnoreCase("done")) { 
      Toast.makeText(Mainactivity.this,"inside done", Toast.LENGTH_LONG).show(); 
     } 
    } 
} 

Cuando abro mi texto a voz aplicación funcionando bien. Pero cómo detectar si texto a voz se completó o no. Necesito ayuda ..... Gracias .....

Respuesta

7

Si está utilizando el nivel de API 15 o posterior puede establecer un escucha de progreso en su referencia TextToSpeech usando

setOnUtteranceProgressListener(UtteranceProgressListener listener) 

Recibirá devoluciones de llamadas que informan el progreso del TTS, incluida una devolución de llamada cuando haya finalizado. Ver http://developer.android.com/reference/android/speech/tts/TextToSpeech.html y http://developer.android.com/reference/android/speech/tts/UtteranceProgressListener.html

Sin embargo, veo que ya está usando el OnUtteranceCompletedListener obsoleto. ¿Recibe las devoluciones de llamada en onUtteranceCompleted()? Eso también debería funcionar.

+0

Hola David I intentaron que la solución pero me da error para setOnUtteranceProgressListener.And para que onUtteranceCompleted se ejecuta sin un error, pero no da el mensaje enUnidad completada, por lo que hay forma de resolver este problema. Si estoy haciendo algo mal. Necesito ayuda ... – nilkash

+1

Llama a 'int result = tts.setOnUtteranceCompletedListener (thi s);' para establecer el oyente. Compruebe el valor de la variable 'result'. SUCCESS (0) o ERROR (-1) deberían regresar. Además, agregue un poco de registro a 'onUtteranceCompleted()' para ver si realmente llega allí. También verifica tu logcat por cualquier otro error extraño. –

+0

Gracias David gracias por la respuesta. Funciona bien. Uso el registro en lugar de pan tostado y funciona bien. Gracias... – nilkash

3

Aquí hay un código de here que le ayuda a ser compatible hacia atrás por lo que no tiene que apuntar 15.

private void setTtsListener() 
    { 
     final SpeechRecognizingAndSpeakingActivity callWithResult = this; 
     if (Build.VERSION.SDK_INT >= 15) 
     { 
      int listenerResult = tts.setOnUtteranceProgressListener(new UtteranceProgressListener() 
      { 
       @Override 
       public void onDone(String utteranceId) 
       { 
        callWithResult.onDone(utteranceId); 
       } 

       @Override 
       public void onError(String utteranceId) 
       { 
        callWithResult.onError(utteranceId); 
       } 

       @Override 
       public void onStart(String utteranceId) 
       { 
        callWithResult.onStart(utteranceId); 
       } 
      }); 
      if (listenerResult != TextToSpeech.SUCCESS) 
      { 
       Log.e(TAG, "failed to add utterance progress listener"); 
      } 
     } 
     else 
     { 
      int listenerResult = tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() 
      { 
       @Override 
       public void onUtteranceCompleted(String utteranceId) 
       { 
        callWithResult.onDone(utteranceId); 
       } 
      }); 
      if (listenerResult != TextToSpeech.SUCCESS) 
      { 
       Log.e(TAG, "failed to add utterance completed listener"); 
      } 
     } 
    } 
7

Llame al setOnUtteranceCompletedListener dentro de la función del objeto onInit TTS.

Si desea realizar cambios en la IU en la llamada de la función onUtteranceCompleted, agregue el código dentro de un método runOnUIThread.

Y recuerde agregar el valor Hashmap parámetro al llamar a la función de hablar()

Ejemplo:

TextToSpeech tts= new TextToSpeech(context, new OnInitListener() { 

@Override 
public void onInit(int status) { 

    mTts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() { 

     @Override 
     public void onUtteranceCompleted(String utteranceId) { 

      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
       //UI changes 
       } 
      }); 
     } 
    }); 

} 
}); 


HashMap<String, String> params = new HashMap<String, String>(); 

params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,"stringId"); 

tts.speak("Text to Speak",TextToSpeech.QUEUE_FLUSH, params); 
Cuestiones relacionadas