Rez*_*eza 5 java android text-to-speech
我正在使用一个简单的代码来使用 Text-To-Speech:
package ch.yourclick.kitt.fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.Locale;
import ch.yourclick.kitt.R;
/**
* A simple {@link Fragment} subclass.
* Use the {@link GeneralFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class GeneralFragment extends Fragment {
private TextToSpeech tts;
public GeneralFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @return A new instance of fragment General.
*/
// TODO: Rename and change types and number of parameters
public static GeneralFragment newInstance() {
GeneralFragment fragment = new GeneralFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_general, container, false);
Button hello = view.findViewById(R.id.hello);
// Text to speech
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) { // <-- I never get into that if statement
int result = tts.setLanguage(Locale.getDefault());
// Language is not supported
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
}
else {
Log.e("TTS", "" + status); // Returns -1
Log.e("TTS", "" + TextToSpeech.SUCCESS); // Returns 0
}
}
});
hello.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
speak();
}
});
return view;
}
/**
* Speak
*/
private void speak() {
String text = "Hello";
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Turn off
*/
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
Run Code Online (Sandbox Code Playgroud)
我收到消息:
W/TextToSpeech:说话失败:未绑定到 TTS 引擎
我的问题是无法初始化 Text To Speech:
status返回-1并TextToSpeech.SUCCESS返回0。
我正在使用 Android Studio,我的虚拟设备是Pixel 2 API 30。所以Google Text-to-speech Engine好像装在上面了:
设置 -> 辅助功能 -> 文本到语音输出
如果我点击Play,我会听到一个声音,所以我知道这不应该是设备问题。但为什么它不适用于我的应用程序?我没有得到任何错误。
我不知道我做错了什么。如果您知道答案或对它可能是什么有任何建议,请告诉我!
| 归档时间: |
|
| 查看次数: |
943 次 |
| 最近记录: |