在Android中制作文本到语音包装语音、文本、Android

2023-09-06 23:30:54 作者:冷眼看你装

我试图创建一个谷歌Android的文本到语音功能的包装类。但是,我无法找到一种方法让系统暂停,直到OnInit函数完成后。底部附件是我基于什么我发现这里创建了一个解决方案中的内容:http://stackoverflow.com/questions/1160876/android-speech-how-can-you-read-text-in-android

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: http://stackoverflow.com/questions/1160876/android-speech-how-can-you-read-text-in-android

然而,这个解决方案似乎不工作。为什么这可能不工作,或者是任何想法,将是一个好主意,以确保任何说话()调用我的OnInit后发生()调用?

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?

公共类SpeechSynth实现OnInitListener{

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

}

我已经能够让这个我可以通过构造函数传递文本字符串,然后把它在OnInit()函数播放。不过,我真的想避免破坏并重新创建整个文本到语音转换引擎每次我需要我的程序时说不同的东西。

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.

推荐答案

我建议你靠锁,而不是你的准备状态INT。将code如下:

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