Android speech - how can you read text in Android?

后端 未结 5 1567
一生所求
一生所求 2021-01-07 05:09

How can you read data, i.e. convert simple text strings to voice (speech) in Android?

Is there an API where I can do something like this:

TextToVoice         


        
5条回答
  •  时光取名叫无心
    2021-01-07 05:53

    Using the TTS is a little bit more complicated than you expect, but it's easy to write a wrapper that gives you the API you desire.

    There are a number of issues you must overcome to get it work nicely.

    They are:

    1. Always set the UtteranceId (or else OnUtteranceCompleted will not be called)
    2. setting OnUtteranceCompleted listener (only after the speech system is properly initialized)
    
    public class TextSpeakerDemo implements OnInitListener
     {
        private TextToSpeech tts;
        private Activity activity;
    
        private static HashMap DUMMY_PARAMS = new HashMap();
        static 
        {
            DUMMY_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "theUtId");
        }
        private ReentrantLock waitForInitLock = new ReentrantLock();
    
        public TextSpeakerDemo(Activity parentActivity)
        {
            activity = parentActivity;
            tts = new TextToSpeech(activity, this);       
            //don't do speak until initing
            waitForInitLock.lock();
        }
    
        public void onInit(int version)
        {        //unlock it so that speech will happen
            waitForInitLock.unlock();
        }  
    
        public void say(WhatToSay say)
        {
            say(say.toString());
        }
    
        public void say(String say)
        {
            tts.speak(say, TextToSpeech.QUEUE_FLUSH, null);
        }
    
        public void say(String say, OnUtteranceCompletedListener whenTextDone)
        {
            if (waitForInitLock.isLocked())
            {
                try
                {
                    waitForInitLock.tryLock(180, TimeUnit.SECONDS);
                }
                catch (InterruptedException e)
                {
                    Log.e("speaker", "interruped");
                }
                //unlock it here so that it is never locked again
                waitForInitLock.unlock();
            }
    
            int result = tts.setOnUtteranceCompletedListener(whenTextDone);
            if (result == TextToSpeech.ERROR)
            {
                Log.e("speaker", "failed to add utterance listener");
            }
            //note: here pass in the dummy params so onUtteranceCompleted gets called
            tts.speak(say, TextToSpeech.QUEUE_FLUSH, DUMMY_PARAMS);
        }
    
        /**
         * make sure to call this at the end
         */
        public void done()
        {
            tts.shutdown();
        }
    }
    

提交回复
热议问题