android 如何将简单的文本转换为语音

hiz5n14c  于 2022-12-09  发布在  Android
关注(0)|答案(2)|浏览(147)

我一直在尝试做一个简单的文本到语音的应用程序,通过尝试从youtube和教程网站的样本代码,似乎没有为我工作。发言人失败:未绑定到TTS引擎”
下面是我正在尝试的当前代码

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
Button speakBtn;
EditText speakText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    speakText = (EditText) findViewById(R.id.txtSpeak);
    speakBtn = (Button)findViewById(R.id.btnSpeech);
    textToSpeech = new TextToSpeech(this, this);
    speakBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            texttoSpeak();
        }
    });
}
@Override
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        int result = textToSpeech.setLanguage(Locale.US);
        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("error", "This Language is not supported");
        } else {
            texttoSpeak();
        }
    } else {
        Log.e("error", "Failed to Initialize");
    }
}
@Override
public void onDestroy() {
    if (textToSpeech != null) {
        textToSpeech.stop();
        textToSpeech.shutdown();
    }
    super.onDestroy();
}
private void texttoSpeak() {
    String text = speakText.getText().toString();
    if ("".equals(text)) {
        text = "Please enter some text to speak.";
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
    }
    else {
        textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }
}}

对不起,我知道的还不多,如果能得到帮助,我将不胜感激。提前感谢

w46czmvw

w46czmvw1#

这是我的解决方案,通过这种方式,代码选择设备中使用的语言:

private TextToSpeech tts;

@Override
public void onResume() {
    super.onResume();
    //((AppCompatActivity) getActivity()).getSupportActionBar().hide();
    tts = new TextToSpeech(requireContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                //int result = tts.setLanguage(Locale.forLanguageTag("en-US"));
                int result = tts.setLanguage(Locale.forLanguageTag(Locale.getDefault().toLanguageTag()));
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.e("TTS", "The Language not supported!");
                } else {
                    Log.d("TTS", "TTS its working");
                }
            }
        }
    });
}

// in your code
tts.speak("read this", TextToSpeech.QUEUE_FLUSH, null, "");

@Override
public void onPause() {
    if (tts != null) {
        tts.stop();
        tts.shutdown();
    }
    super.onPause();
}

相关问题