我尝试在我的项目中使用语音识别器。 我以本教程为例。
link 当我使用该按钮开始收听时,一切正常。
binding.toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
binding.progressSound.setVisibility(View.VISIBLE);
binding.progressSound.setIndeterminate(true);
requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO}, REQUEST_RECORD_PERMISSION);
} else {
binding.progressSound.setIndeterminate(false);
binding.progressSound.setVisibility(View.INVISIBLE);
speech.stopListening();
}
}
});
SpeechRecognizer.startListening方法已覆盖onRequestPermissionsResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_RECORD_PERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//===start listening
speech.startListening(recognizerIntent);
} else {
Toast.makeText(getContext(), "Permission Denied!", Toast
.LENGTH_SHORT).show();
}
}
}
但是当我播放一些声音后启动识别器时,它不起作用。
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp)
{
Log.i(TAG, "endOfSound");
binding.toggleButton.performClick();
}
当我尝试使用延迟解决此问题时,它会起作用。
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
binding.toggleButton.performClick();
}
}, 5000);
但这是一个不好的解决方案,因为声音的长度不同。