语音识别功能无法正常工作:无意中发言,再试一次

时间:2017-04-25 12:08:13

标签: android speech-recognition

我想在我的Android应用中实现语音识别。但是每次我点击按钮打开麦克风时,会弹出一个框,要求点击发言并再试一次。点击按钮时,没有任何反应,也没有录制语音。

这是我的代码;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

private Button openMic;
private TextView showText;
private final int REQ_CODE_SPEECH_OUTPUT = 143;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    openMic = (Button)findViewById(R.id.button);
    showText = (TextView)findViewById(R.id.textView);

    openMic.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btnToOpenMic();
        }
    });
}

private void btnToOpenMic() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
    getIntent().putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak");

    try{
        startActivityForResult(intent, REQ_CODE_SPEECH_OUTPUT);
    }
    catch(ActivityNotFoundException tim){
        Toast.makeText(MainActivity.this, "Message", Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case REQ_CODE_SPEECH_OUTPUT: {
            if (resultCode == RESULT_OK && null != data){
                ArrayList<String> voiceInText = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                showText.setText(voiceInText.get(0));
            }
            break;
        }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

代码没问题。我只是删除了所有Google应用程序使用手机麦克风的权限。

重新启用它解决了问题。