Making a Text-To-Speech Wrapper in Android

╄→гoц情女王★ 提交于 2020-01-14 04:10:07

问题


I am attempting to create a wrapper class for Google Android's Text-To-Speech functionality. However, I'm having trouble finding a way to have the system pause until after the onInit function has finished. Attached at the bottom is something of a solution I created based on what I found here: Android speech - how can you read text in Android?

However, this solution does not seem to work. Any thoughts on why this might not be working, or what would be a good idea in order to make sure that any Speak() calls happen after my onInit() call?

public class SpeechSynth implements OnInitListener {

private TextToSpeech tts;
static final int TTS_CHECK_CODE = 0;
private int ready = 0;
private ReentrantLock waitForInitLock = new ReentrantLock();

SpeechSynth( Activity screen )
{
    ready = 0;
    tts = new TextToSpeech( screen, this );
    waitForInitLock.lock();

}

public void onInit(int status) 
{
    if (status == TextToSpeech.SUCCESS)
    {
        ready = 1;
    }
    waitForInitLock.unlock();
}

public int Speak( String text )
{
    if( ready == 1 )
    {
        tts.speak(text, TextToSpeech.QUEUE_ADD, null);
        return 1;
    }
    else
    {
        return 0;
    }   
}

}

I have been able to make it so that I can pass a string of text through the constructor, then have it played in the onInit() function. However, I would really like to avoid having to destroy and re-create the whole text-to-speech engine every time I need to have my program say something different.


回答1:


I suggest you rely on the lock instead of your ready state int. Insert code as follows:

public int Speak( String text )
{
        if (waitForInitLock.isLocked())
        {
            try
            {
                waitForInitLock.tryLock(180, TimeUnit.SECONDS);
            }
            catch (InterruptedException e)
            {
                Log.e(D_LOG, "interruped");
            }
            //unlock it here so that it is never locked again
            waitForInitLock.unlock();
        }

    if( ready == 1 )
    {
        tts.speak(text, TextToSpeech.QUEUE_ADD, null);
        return 1;
    }
    else
    {
        return 0;
    }   
}


来源:https://stackoverflow.com/questions/2587203/making-a-text-to-speech-wrapper-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!