两个按钮上的语音识别器到两个edittexts

时间:2014-03-18 23:39:05

标签: android speech-recognition

我有两个edittext框和一个按钮。

当我点击第一个按钮时,我想要调用语音识别器,结果进入第一个editext框,第二个按钮填充第二个edittext框。

我使用以下代码

public void speech1(View view) {
    final int REQUEST_CODE = 1;
    Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
    try {
        startActivityForResult(i, REQUEST_CODE);
    } catch (Exception e) {
    Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
    }
}
public void speech2(View view) {
    final int REQUEST_CODE = 2;
    Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
    try {
        startActivityForResult(i, REQUEST_CODE);
    } catch (Exception e) {
        Toast.makeText(this, "Error initializing speech to text engine.",        Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    if(REQUEST_CODE==1){
        EditText editText = (EditText)findViewById(R.id.speechText1);
        editText.setText(thingsYouSaid.get(0), TextView.BufferType.EDITABLE);
    }

    if(REQUEST_CODE==2){        
        EditText editText = (EditText)findViewById(R.id.speechText2);
        editText.setText(thingsYouSaid.get(0), TextView.BufferType.EDITABLE);
    }
}

它不会填写正确的edittext框,只是留下空白一直在寻找一个教程,但无法找到任何两个语音输入的例子

1 个答案:

答案 0 :(得分:1)

生活中并非所有内容都由教程描述,有时您想要自己思考。在您的特定情况下,您的问题是您正在比较全局变量RESULT_CODE而不是onActivityResult的本地参数,

if(REQUEST_CODE==1){
    EditText editText = (EditText)findViewById(R.id.speechText1);

必须是

if(requestCode==1){
    EditText editText = (EditText)findViewById(R.id.speechText1);

请求代码通过参数传递给您,您需要使用它。