簡體   English   中英

在GCMIntentService中實例化TextToSpeech

[英]Instantiating TextToSpeech inside GCMIntentService

所以我有一個問題。 我正在嘗試讓我的應用根據通過GCM收到的消息來執行操作。 在這種情況下,應該使用TextToSpeech類發出聲音。 效果不錯,但不是我第一次發送郵件。 我意識到這可能是因為TextToSpeech尚未實例化,但是我不確定該怎么做? 我嘗試了onInit(),但這根本不起作用。

另外,在我的示例中,關閉TTS的最佳方法是什么?

免責聲明:我來自PHP背景,對Java知之甚少。 我嘗試邊做邊學,所以如果這是一個愚蠢的問題,請原諒我。 提前致謝!

public class GCMIntentService extends GCMBaseIntentService {

private static final String TAG = "GCMIntentService";
public static TextToSpeech mtts;

public GCMIntentService() {
    super(SENDER_ID);
}

@Override
protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    String message = intent.getExtras().getString("message");
    mtts = new TextToSpeech(context, null);

    if (message.startsWith("makeSound")) {
        mtts = new TextToSpeech(context, null);
        mtts.setLanguage(Locale.US);
        mtts.speak(message, TextToSpeech.QUEUE_FLUSH, null);
    }
}
}

第一次無效,因為TextToSpeech的初始化是異步的。 您不能簡單地實例化它並按需使用它。 如果您想立即使用TextToSpeech,則應提供一個一旦初始化TextToSpeech即可調用的回調。

 mTextToSpeech = new TextToSpeech( this, new TextToSpeech.OnInitListener()
    {
        @Override
        public void onInit( int status )
        {
            // Check for status might not be initialized due to errors
            // Configure language/speed
        }
    } );

其余時間都可以使用,因為mtts是靜態的。 這意味着這是一個類變量,在創建服務的新實例時不會被破壞/初始化。 第二次使用該服務時,該變量已在第一次服務執行中初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM