我正在尝试将文本写入语音应用程序,而我的所有代码都很好。我想执行一些代码完成时。我不知道写什么和在哪里编写该代码。我尝试找到许多解决方案,但它们对我不起作用。请帮助我。预先感谢。
public class Main extends AppCompatActivity {
private TextToSpeech tts;
private EditText et;
private SeekBar sb_pitch;
private SeekBar sb_speed;
private Button bt;
private Button bt2;
private Button bt3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt = findViewById(R.id.bt);
bt2 = findViewById(R.id.bt2);
bt3 = findViewById(R.id.bt3);
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if(status == TextToSpeech.SUCCESS)
{
tts.setLanguage(Locale.ENGLISH);
bt.setEnabled(true);
}
}
});
et = findViewById(R.id.et);
sb_pitch = findViewById(R.id.sb_pitch);
sb_speed = findViewById(R.id.sb_speed);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(et.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"No Text Detected!",Toast.LENGTH_SHORT).show();
}
else
{
bt.setEnabled(false);
sb_pitch.setEnabled(false);
sb_speed.setEnabled(false);
speak();
}
}
});
bt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tts.stop();
bt.setEnabled(true);
sb_pitch.setEnabled(true);
sb_speed.setEnabled(true);
}
});
bt3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (tts.isSpeaking())
{
et.setText("");
bt.setEnabled(false);
sb_pitch.setEnabled(false);
sb_speed.setEnabled(false);
}
else {
et.setText("");
bt.setEnabled(true);
sb_pitch.setEnabled(true);
sb_speed.setEnabled(true);
sb_pitch.setProgress(50);
sb_speed.setProgress(50);
}
}
});
}
private void speak()
{
String text = et.getText().toString();
float pitch = (float)sb_pitch.getProgress() / 50;
if(pitch<0.1)pitch = 0.1f;
float speed = (float)sb_speed.getProgress() / 50;
if(speed<0.1)speed = 0.1f;
tts.setPitch(pitch);
tts.setSpeechRate(speed);
tts.speak(text,TextToSpeech.QUEUE_FLUSH,null);
}
@Override
protected void onDestroy() {
if(tts!=null)
{
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
任何帮助将不胜感激:(
这就是我在应用程序上做的方式
textToSpeech=new TextToSpeech(this, new TextToSpeech.OnInitListener() {
@Override
public void onInit(int status) {
if (status==TextToSpeech.SUCCESS){
int result=textToSpeech.setLanguage(Locale.ENGLISH);
if (result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.i("TextToSpeech","Language Not Supported");
}
textToSpeech.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Log.i("TextToSpeech","On Start");
}
@Override
public void onDone(String utteranceId) {
Log.i("TextToSpeech","On Done");
}
@Override
public void onError(String utteranceId) {
}
});
}else {
Log.i("TextToSpeech","Initialization Failed");
}
}
});
然后在您的按钮上单击
textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null,TextToSpeech.ACTION_TTS_QUEUE_PROCESSING_COMPLETED);