Google Text To Speech 作为一个单独的类,可以在需要时调用? [英] Google Text To Speech as a sperate class that can be called when ever needed?

查看:56
本文介绍了Google Text To Speech 作为一个单独的类,可以在需要时调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 Google TTS 引擎编写语音输出类.但是在整个互联网上,我只找到了在 MainActivity 的 onCreate 和其他覆盖方法中使用布局和使用 TTS 服务的示例.

I've been trying to write a speech output class by using Google TTS engine. But all over the internet, I only find the examples with layout and using the TTS service in the MainActivity's onCreate and other overridden methods.

我想创建一个类,它有一个像 speakThis(String someText) 这样的方法来说出传递的字符串.

I want to make a class that has a method like speakThis(String someText) which speaks out the passed string.

推荐答案

你需要的是一个服务,这是我使用的:

What you need is a Service, here's the one I use:

    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");
            }
        }
    }

当你想调用它时,你只需:

And when yo want to invoke it, you just:

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);

希望有帮助!

这篇关于Google Text To Speech 作为一个单独的类,可以在需要时调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆