Pregunta

Estoy tratando de implementar tecnología de texto a voz de android en mi Actividad, pero me enfrento a un extraño error.No puedo escuchar ningún sonido, a partir de mi código.El hablar método sólo funciona si la pongo en el método onInit, si no, no hablar.

Mi código es el siguiente :

public class GameOverActivity extends Activity implements OnInitListener {
private TextToSpeech talker;
....
talker = new TextToSpeech(this, this);  
say("Something",false);
...
   public void onInit(int status) {  
        if (status == TextToSpeech.SUCCESS) {
          talker.setLanguage(Locale.US);
        }
        else if (status == TextToSpeech.ERROR) {
            Toast.makeText(this,"Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
        }

void say(String text, boolean flush) {
         if(flush == true)
         {
        talker.speak(text,TextToSpeech.QUEUE_FLUSH,null);
         }
         if(flush == false)
         {
        talker.speak(text,TextToSpeech.QUEUE_ADD,null);
         }         
    }

Lo extraño es que si pongo el decir método onInit, funciona bien!

Vi logcat cuidadosamente y aquí están los resultados :

TtsService.OnCreate () TTs se está cargando AudioTrack comenzó TTSService.setLanguage cargado en-US succusfully ajuste de la velocidad de la voz a 100

y entonces no pasa nada.

Cualquier idea acerca de lo que está mal con el código anterior?

Gracias de antemano!

¿Fue útil?

Solución

Después de algunas horas más buscando el código, noté que el problema es que la inicialización del motor TTS toma algún tiempo.Si la inicialización no ha terminado, la llamada del método de voz fallará.

Si "dice" algo en el botón, probablemente no necesitará esto, porque el usuario tomará algún tiempo para pensar antes de presionar el botón, y la inicialización se acabará.

Si desea "decir" algo tan pronto que finaliza la inicialización, use este código:

talker = new TextToSpeech(this, new TextToSpeech.OnInitListener() {

        @Override
        public void onInit(int arg0) {
       if(arg0 == TextToSpeech.SUCCESS) 
           {
        talker.setLanguage(Locale.US);
            say(gameover,true);
            say(line,false);
            say(definition_string,false);
            }
        }
    });

Otros consejos

Se recomienda implementar TextToSpeech.OnInitListener de su actividad principal.intente esto

public class GameOverActivity extends Activity implements TextToSpeech.OnInitListener {

@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {

        int result = mTts.setLanguage(Locale.US);
        // Try this someday for some interesting results.
        // int result mTts.setLanguage(Locale.FRANCE);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
            // Lanuage data is missing or the language is not supported.
            //Log.e(TAG, "Language is not available.");
        } else {
            // Check the documentation for other possible result codes.
            // For example, the language may be available for the locale,
            // but not for the specified country and variant.

            // The TTS engine has been successfully initialized.
            // Allow the user to press the button for the app to speak again.
            // mAgainButton.setEnabled(true);
            // Greet the user.
            //sayHello();
        }
    } else {
        // Initialization failed.

    }

}

private TextToSpeech mTts;
}

También otra causa de este problema podría ser su motor de TTS, a Veces en los teléfonos SAMSUNG el defecto motor de TTS es SAMSUNG Motor que no funciona en algunos idiomas como el persa (no me refiero a los de texto persa, Incluso si usted está tratando de leer un texto en inglés, aún así no funciona, es extraño, pero sucede).Con el fin de resolver todo lo que tienes que hacer es establecer el motor de TTS en el código (o seleccione Setting -> Language input -> Text to speech -> Google Text-to-speech manualmente)

Un problema que he tenido con texto a voz es que si está instalado en la tarjeta SD, no funcionará cuando se enchufe el USB.Por lo tanto, puede intentar desenchufar su dispositivo de prueba desde el USB y ver si eso resuelve el problema.

Otra cosa que podría intentar es pasar por el programa y ver si está alterando su objeto de texto a voz de alguna manera en caso de accidente.Establezca un punto de interrupción en la parte de conversación de su código y eche un vistazo a todas las variables en su objeto de hablador.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top