文本转语音:API Level 21中已弃用的speak函数

28

我尝试在我的应用程序中使用 TextToSpeech,

String text = editText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

但是在API Level 21中,函数speak(String text, int queueMode, HashMap params)已被弃用。建议使用speak(CharSequence text, int queueMode, Bundle params, String utteranceId)代替。 但我不知道如何设置它。谢谢。

2个回答

61
String text = editText.getText().toString();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    tts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
} else {
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

当我使用你的建议时,Android Studio 会显示:"params="null" utteranceId="null",并取消if语句建议。但这对我的情况帮助不够大。 - Bay
Build.VERSION_CODES现已过时(2021年4月)。只需替换上述条件(Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)...等。 - Albert

-1

以下是完整的工作代码,适用于我的情况

Private TextToSpeech ts
 ts=new TextToSpeech(CurrentActivity.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                String text = "Any Text to Speak";
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    ts.speak(text,TextToSpeech.QUEUE_FLUSH,null,null);
                } else {
                    ts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
                }

            }
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接