我从互联网上复制了这个,其他人说这是有效的,但是当我尝试的时候 说它没有做任何事情。
我尝试在方法onBeginingOfSpeech()之外编写有关意图的代码,但它确实有效。
public class Schermata extends ActionBarActivity implements RecognitionListener{
SpeechRecognizer speechRecognizer;
TextView test;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schermata);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
test = (TextView) findViewById(R.id.test);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_schermata, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onReadyForSpeech(Bundle params) {
test.setText("INIZIO");
}
@Override
public void onBeginningOfSpeech() {
test.setText("INIZIO");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer.startListening(intent);
}
@Override
public void onRmsChanged(float rmsdB) {
}
@Override
public void onBufferReceived(byte[] buffer) {
}
@Override
public void onEndOfSpeech() {
test.setText("FINE");
}
@Override
public void onError(int error) {
}
@Override
public void onResults(Bundle results) {
ArrayList<String> res = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String s = "";
for (String result : res)
s += result + "\n";
test.setText(s);
}
@Override
public void onPartialResults(Bundle partialResults) {
}
@Override
public void onEvent(int eventType, Bundle params) {
}
}
答案 0 :(得分:0)
如果我理解正确,当在onBeginningOfSpeech()之外定义Intent时,这对你有用,那么简单地把它放在它之外,把它放在那里是错误的,我会解释。
函数onBeginningOfSpeech()(另外:onResults,onReadyForSpeech等等)在识别器开始工作后被调用,并且只是识别器听到人说话的事件的回调,所以你需要有在调用此函数之前,意图准备就绪并与识别器配对。
尝试创建一个'initialize()'函数,在调用
之前设置所有这些函数speechRecognizer.startListening(intent);
换句话说,使用它,而不是'onBeginningOfSpeech()'上的内容
public void initialize(){
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechRecognizer.startListening(intent);
}
除此之外,你正在以错误的方式使用onResults(),你应该只提取给你的ArrayList的第一个String,其他的只是同一个语音的最差结果。
答案 1 :(得分:0)
<uses-permission android:name="android.permission.RECORD_AUDIO" />
确保清单中有RECORD_AUDIO权限,语音识别在没有它的情况下不起作用。