因此,我使用SpeechRecognizer
和RecognitionListener
来识别用户语音。它工作正常,但问题是当我测试它时,我注意到在我说完之后它不会调用onEndOfSpeech
。它等待大约7到10秒,然后调用onEndOfSpeech
和onResult
。我不知道造成这种延误的原因。
以下是代码:
public class MainActivity extends AppCompatActivity {
protected static final int REQUEST_OK = 1;
SpeechRecognizer sr;
TextView mText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mText = (TextView) findViewById(R.id.text1);
RecognitionListener recognitionListener=new RecognitionListener() {
@Override
public void onReadyForSpeech(Bundle bundle) {
Toast.makeText(MainActivity.this,"Start takling",Toast.LENGTH_SHORT).show();
}
@Override
public void onBeginningOfSpeech() {
}
@Override
public void onRmsChanged(float v) {
}
@Override
public void onBufferReceived(byte[] bytes) {
}
@Override
public void onEndOfSpeech() {
Toast.makeText(MainActivity.this,"onEndOfSpeech",Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int i) {
}
@Override
public void onResults(Bundle bundle) {
Toast.makeText(MainActivity.this,"onResults",Toast.LENGTH_SHORT).show();
ArrayList<String> voiceResults =
bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults != null) {
String text = voiceResults.get(0);
Toast.makeText(MainActivity.this,text,Toast.LENGTH_SHORT).show();
}
}
@Override
public void onPartialResults(Bundle bundle) {
}
@Override
public void onEvent(int i, Bundle bundle) {
}
};
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(recognitionListener);
findViewById(R.id.button1).setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
sr.startListening(intent);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
sr.destroy();
}
}
activity_main.xml中:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="132dp"
android:text="..." ></TextView>
<ImageButton
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/text1"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:layout_marginTop="37dp"
android:src="@android:drawable/ic_btn_speak_now" ></ImageButton>
</RelativeLayout>