gpt4 book ai didi

java - 文本到语音 android 在 Activity 可见时输出语音

转载 作者:行者123 更新时间:2023-12-01 16:38:21 26 4
gpt4 key购买 nike

我正在为视障人士构建一个 Android native 应用程序,并且我想使用 android TTS - android.speech.tts.TextToSpeech 来引导用户使用我的应用程序。我在单击按钮后成功显示了语音,但我也想在 Activity 可见后输出欢迎消息。这是一个代码 fragment :


public class MainActivity extends AppCompatActivity {
private TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
Log.d("TTS","Speech initialized");
}
} else {
Log.e("TTS", "Initialization failed");
}
}
});
speak("welcome");
speak("Click on the button to begin settings ");

audio.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
speak("this is a test");
}
});
}
public void speak(final String S){
textToSpeech.speak(S,TextToSpeech.QUEUE_ADD,null);
}
}

最佳答案

问题是 tts 尚未初始化。

解决这个问题的最快方法就是将介绍性的发言命令移到 onInit 中:

@Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
Log.d("TTS","Speech initialized");

speak("welcome");
speak("Click on the button to begin settings ");
}
} else {
Log.e("TTS", "Initialization failed");
}
}

关于java - 文本到语音 android 在 Activity 可见时输出语音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61912828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com