我想创建简单的Speech to Text应用程序,我找到了SpeechRecognizer
类,它看起来像我需要的东西。
我已将这些权限添加到我的清单中:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
然后在我的MainActivity
中,只有一个button
和一个textVew
。
我已经设置了我的活动onCreate
,如下所示:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
button = (Button) findViewById(R.id.button);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new MySpeechRecognitionListener());
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"com.daniyar.speechrecogniitontest");
sr.startListening(intent);
}
});
}
在我的MySpeechRecognitionListener
中看起来像这样:
private class MySpeechRecognitionListener implements RecognitionListener {
@Override
public void onReadyForSpeech(Bundle bundle) {
Toast.makeText(MainActivity.this, "Ready", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(int i) {
Toast.makeText(MainActivity.this, "Error " + i, Toast.LENGTH_LONG).show();
}
@Override
public void onResults(Bundle bundle) {
String str = "";
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0 ; i < data.size(); i++) {
str += data.get(i);
}
textView.setText(str);
}
}
当我启动我的应用程序然后点击按钮时,它会显示我Error 5
的祝酒词,并在我的日志中显示一条消息:
SpeechRecognizer: no selected voice recognition service
如何设置识别服务?此外,是否可以离线使用SpeechRecognizer?