5

Estoy implementando la lectura de texto con voz en .

El código funciona, pero me encuentro con la dificultad de que TextToSpeech no puede leer más de 4000 caracteres a la vez.

¿Cómo podría hacer para que mi método me lea todo el texto cuando éste supere el límite permitido por TextToSpeech?

NOTA DE EDICIÓN:

Al parecer la forma más idónea es crear un mecanismo que separe el texto en varias partes y lo lea en una especie de cola de lecturas Probé a leer las diferentes partes llamando dentro de un bucle tts.speak(parteDelTexto, TextToSpeech.QUEUE_ADD, bundle, null)pero sólo lee la primera ocurrencia del bucle.

He estado investigando y en varios sitios hablan de usar QUEUE_ADD y onUtterance, pero no doy con la forma de implementar o crear esa cola de lectura.

Este es mi código:

Función invocada al hacer click en el icono de lectura:

public void ttsFunction() {
        tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    Locale locSpanish = new Locale("spa", "ESP");
                    int result = tts.setLanguage(locSpanish);
                    if (result == TextToSpeech.LANG_MISSING_DATA
                            || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Toast.makeText(getApplicationContext(), "Lenguaje no soportado", Toast.LENGTH_SHORT).show();
                    } else {
                        Log.v(TAG, "onInit exitoso");
                        final TextView mTextView = (TextView) findViewById(R.id.txt_oficio);

                        String strTexto = mTextView.getText().toString();
                        leerTexto(strTexto);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Falló la inicialización", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

Función de lectura de voz propiamente

Limitando el contenido de esta manera strTexto = strTexto.substring(0,3999); funciona, pero yo quiero leer todo el texto.

void leerTexto(String strTexto){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Log.v(TAG, "API 21+");
        Bundle bundle = new Bundle();
        bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
        strTexto = strTexto.substring(0,3999); //Así funciona
        tts.speak(strTexto, TextToSpeech.QUEUE_FLUSH, bundle, null);
    } else {
        Log.v(TAG, "API 15-");
        HashMap<String, String> param = new HashMap<>();
        param.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_MUSIC));
        tts.speak(strTexto, TextToSpeech.QUEUE_FLUSH, param);
    }
}
2
  • Nunca he usado TTS pero has intentado separa el texto por cada 3999 caracter? Osea como un tipo de split y luego cuando termine de leer el primero continuas en el segundo y asi por el estilo.
    – Einer
    el 11 oct. 2017 a las 14:56
  • He pensando en hacer eso @Einer, pero quisiera saber si se puede hacer con la misma clase TextToSpeech, o sea, si la misma tiene algún modo de uso que maneje ese tipo de situaciones. Es la primera vez que la uso, pero es muy interesante, aunque hace algunas cosas raras cuando lee... Pero eso sería objeto para otra pregunta.
    – A. Cedano
    el 11 oct. 2017 a las 15:03

2 respuestas 2

3

En realidad la limitación usando TextToSpeech es la obtenida por getMaxSpeechInputLength() que es actualmente definida en 4000 caracteres.

public static int getMaxSpeechInputLength() {
    return 4000;
}

La opción aquí es separar la reproducción del texto por bloques, sin embargo esto tendrá como resultado una pausa al reproducir cada bloque.

En base a esta limitación por experiencia propia se tuvo que realizar un proceso por lotes para generar los audios de los textos, pero mediante otra opción, al tener los url del mp3 se reproducen mediante MediaPlayer.

1
  • Son textos dinámicos que cambian cada día. En mi caso no sería factible generar MP3 y alojarlos donde quiera que sea... ¿Ninguna opción para aumentar la capacidad de TTS? ¿La pausa que dices al leer por bloques es larga, notoria... depende de algo, como capacidad del dispositivo etc?
    – A. Cedano
    el 11 oct. 2017 a las 16:52
1

He logrado resolver el problema usando UtteranceProgressListener, el cual permite agregar a cada texto enviado al lector una id de utterance (una id de sonido podríamos decir).


Al implementarlo, cada vez que un sonido termina de reproducirse, retorna al método onDone(String utteranceId) con el id del sonido que acaba de leer.

Esto, combinado con TextToSpeech.QUEUE_ADD en el método leerTexto permite ir agregando a la lista de reproducción los diferentes textos que vayamos obteniendo dentro de un bucle o fuera de él.

Este es el código, sin duda mejorable en algunos aspectos (por ejemplo, todavía le falta controlar que cualquiera de las cadenas ya divididas no exceda de todos modos el máximo de caracteres permitidos). El hecho es que funciona de la forma esperada.

Método que crea el lector y le pasa los textos

public void ttsFunction() {
    tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                final Locale locSpanish = new Locale("spa", "ESP");
                int result = tts.setLanguage(locSpanish);
                if (result == TextToSpeech.LANG_MISSING_DATA
                        || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(getApplicationContext(), "Lenguaje no soportado", Toast.LENGTH_SHORT).show();
                } else {

                    tts.setOnUtteranceProgressListener(
                            new UtteranceProgressListener() {
                                @Override
                                public void onStart(String s) {
                                    //Log.i(TAG,"Start: "+s);
                                    final TextView mTextView = (TextView) findViewById(R.id.txt_oficio);
                                    String strTexto = mTextView.getText().toString();
                                    String PARAGRAPH_SPLIT_REGEX = "…";
                                    String[] strPrimera = strTexto.split(PARAGRAPH_SPLIT_REGEX);
                                    strPartes = strPrimera[0].split("_");
                                    strOracion = strPrimera[1];

                                }

                                @Override
                                public void onDone(String s) {
                                    Log.i(TAG, "Done: " + s);

                                    for (String textos : strPartes) {
                                        i = 1;
                                        x = i - 1;
                                        StringBuilder sb = new StringBuilder();
                                        sb.append("");
                                        sb.append(i);
                                        strActual = sb.toString();

                                        StringBuilder sbX = new StringBuilder();
                                        sbX.append("");
                                        sbX.append(x);
                                        strPrevia = sbX.toString();

                                        if (s.equals(strPrevia)) {
                                            leerTexto(textos, strActual);
                                            i++;

                                        }

                                    }
                                    leerTexto(strOracion, "Oracion");
                                    leerTexto("Fin del Oficio", "fin");
                                    if (s.equals("fin")) {
                                        //Log.i(TAG, "Cerramos...");
                                        tts.stop();
                                        tts.shutdown();
                                    }

                                }

                                @Override
                                public void onError(String s) {
                                    Log.i(TAG, "Error: " + s);
                                    //Toast.makeText(OficioActivity.this, "OnError mensaje", Toast.LENGTH_SHORT).show();
                                }
                            });

                    Log.i(TAG, "onInit exitoso");
                    //Texto inicial
                    leerTexto("Iniciando oración...", "0");

                }
            } else {
                Toast.makeText(getApplicationContext(), "Falló la inicialización", Toast.LENGTH_SHORT).show();
            }

        }
    });
}

Método para leer

void leerTexto(String strTexto, String strId) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //API 21+
        Bundle bundle = new Bundle();
        bundle.putInt(TextToSpeech.Engine.KEY_PARAM_STREAM, AudioManager.STREAM_MUSIC);
        tts.speak(strTexto, TextToSpeech.QUEUE_ADD, bundle, strId);
    } else {
        //API 15-
    }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.