Android演讲 - 如何在Android中阅读文字?

时间:2009-07-21 18:25:57

标签: android text-to-speech

如何在Android中读取数据,即将简单文本字符串转换为语音(语音)?

是否有API我可以做这样的事情:

TextToVoice speaker = new TextToVoice();
speaker.Speak("Hello World");

5 个答案:

答案 0 :(得分:3)

使用TTS比您预期的要复杂一点,但是编写一个能够为您提供所需API的包装器很容易。

为了让它正常运行,你必须克服许多问题。

他们是:

  1. 始终设置UtteranceId(否则 OnUtteranceCompleted将不会 叫)
  2. 设置OnUtteranceCompleted 听众(仅在演讲结束后 系统已正确初始化)
  3. 
    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();
        }
    }
    

答案 1 :(得分:2)

Here you goA tutorial on using the library最大的缺点是它需要一张SD卡来存储声音。

答案 2 :(得分:1)

可以在“Pro Android 2 book”中找到tts使用的一个很好的工作示例。看看第15章的源代码。

答案 3 :(得分:0)

有第三方文字转语音引擎。有传言说Donut包含一个文本到语音引擎,暗示它将在未来的Android版本中提供。不过,除此之外,Android中还没有内置任何文本转语音功能。

答案 4 :(得分:0)

甜甜圈有这个:请参阅android.speech.tts包。