close

1.啟動原生google search voice來取得辨識文字

自定義回傳code

private final static int REQUEST_CODE = 200;

啟動google voice

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "請說~");
startActivityForResult(intent,REQUEST_CODE);

取得google voice 辨識List

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_CODE){
        if(resultCode == RESULT_OK && data != null){
            ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            Log.d(TAG, "onActivityResult: "+result.get(0));
        }
    }
}

 

2.使用RecognitionListener進行背景錄音+辨識(start、destroy為控制function)

public class VoiceEngine implements RecognitionListener  {
    public MutableLiveData<ArrayList<String>> voiceList = new MutableLiveData();//辨識文字陣列
    public MutableLiveData<String> voiceWord = new MutableLiveData();//辨識文字
    public MutableLiveData<Integer> errorCode = new MutableLiveData();//錯誤代碼
    public MutableLiveData<Float> Rms = new MutableLiveData<>();//分貝

    private SpeechRecognizer recognizer;
    private Intent speechIntent;
    public VoiceEngine(Context context) {
        recognizer = SpeechRecognizer.createSpeechRecognizer(context);
        recognizer.setRecognitionListener(this);
        speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    }
    public void start(){
        recognizer.startListening(speechIntent);
    }
    public void destroy(){
        recognizer.stopListening();
        recognizer.destroy();
    }
    @Override
    public void onReadyForSpeech(Bundle params) {

    }

    @Override
    public void onBeginningOfSpeech() {

    }

    @Override
    public void onRmsChanged(float rmsdB) {
        Rms.setValue(rmsdB);
    }

    @Override
    public void onBufferReceived(byte[] buffer) {

    }

    @Override
    public void onEndOfSpeech() {

    }

    @Override
    public void onError(int error) {
        errorCode.setValue(error);
    }

    @Override
    public void onResults(Bundle results) {
        voiceList.setValue(results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION));
        voiceWord.setValue(results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION).get(0));
    }

    @Override
    public void onPartialResults(Bundle partialResults) {

    }

    @Override
    public void onEvent(int eventType, Bundle params) {

    }

}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JBLin 的頭像
    JBLin

    a0973378273的部落格

    JBLin 發表在 痞客邦 留言(0) 人氣()