将麦克风上的麦克风保持为文字

时间:2017-07-20 05:32:00

标签: android speech-to-text

当我点击麦克风按钮时我想要麦克风,当我再次点击麦克风按钮然后它关闭。 我有一个代码,请指导我如何保持麦克风。 例如,当我点击麦克风按钮时,它开始聆听,当我再次点击麦克风时,它就会停止聆听。

public class MainActivity extends AppCompatActivity {

    private static final int REQ_CODE_SPEECH_INPUT = 100;
    private TextView mVoiceInputTv;
    private ImageButton mSpeakBtn;

    private String[] myWords = {"start","stop","deactivate","activate","scan"};
    private ArrayList<String> arrayList=new ArrayList<>();
    boolean isStart;
    String strings;
    String start="start";
    String stop="stop";

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

        mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
        mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
        mSpeakBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mVoiceInputTv.setText("");
                startVoiceInput();
            }
        });
    }

    private void startVoiceInput() {
        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());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hello, Please Speak somethings");
        try {
            startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
        } catch (ActivityNotFoundException a) {
        }
    }

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

        switch (requestCode) {
            case REQ_CODE_SPEECH_INPUT: {
                if (resultCode == RESULT_OK && null != data) {
                    ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    TextView n=new TextView(this);
                    if  (((result.get(0).toLowerCase()).contains(start))&&result.get(0).contains(stop)) {
                      strings = getBetweenStrings(result.get(0), start, stop);
                        mVoiceInputTv.setText("" + strings);
                    }
                        Log.d("action","String "+strings+ "  result "+result.get(0)+" "+result.get(0).equals(myWords[0].toLowerCase()));
                    }
            }
        }
    }
    public static String getBetweenStrings(
            String text,
            String textFrom,
            String textTo) {

        String result = "";
        result = text.substring(text.indexOf(textFrom) + textFrom.length(), text.length());
        result = result.substring(0, result.indexOf(textTo));

        return result;
    }
}

0 个答案:

没有答案