我有一个maind UI类,它有一个按钮,用于实例化一个实现SpeechRecognizer库的类来转换文本中的语音。
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startNoiseProcessService();
}
});
startNoiseProcessService()是一个调用另一个类对象的函数。
public void startNoiseProcessService() {
StreamService ss = new StreamService(this);
String s = ss.startStreaming();
if ( s.equals("NA") ) {
Toast t = Toast.makeText(getApplicationContext(),threadCnt +
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
StreamService 类实现 SpeechRecognizer API 。
这个StreamService类被称为完全正常,问题在于,在onResults(Bundle)
方法计算结果后,我无法从语音中获取转换后的文本。
我需要转换的文本来更新我的文本框,而我却没有得到它。
startStreaming()实现:
public String startStreaming() {
text = "";
if ( !SpeechRecognizer.isRecognitionAvailable(context) ) {
text = "NA";
return text;
}
Log.d(TAG, "started taking input");
sr = SpeechRecognizer.createSpeechRecognizer(context);
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);
sr.setRecognitionListener( new mylistener());
sr.startListening(intent);
}
答案 0 :(得分:1)
根据您的评论,我认为您在调用sr.startListening(intent)
时无法获得结果。您需要使用侦听器的onResults
方法获取结果,并从那里处理Bundle
内的文本。
我实施此方法的方法是让Service
负责处理SpeechRecognizer
。然后,当调用onResults
时,我使用消息处理程序将文本发送回原始调用者。您可以在此处查看有关如何执行此操作的详细信息:https://developer.android.com/training/multiple-threads/communicate-ui.html