语音识别和翻译

时间:2019-06-30 17:40:05

标签: java android speech-recognition

我有一个正常运行的语音转文本应用程序,我想实现“语音转译文本”功能,因此,当用户使用特定语言讲话时,它会被翻译成英语并显示为文本,而不是当前显示的原始语音到文本输入。因此,我们需要修改此代码以尽可能做到这一点...

final EditText resultText = findViewById(R.id.resultText);

//Creating and setting up the SpeechRecognizer
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());

mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {

    @Override
    public void onReadyForSpeech(Bundle bundle) {}

    @Override
    public void onBeginningOfSpeech() {}

    @Override
    public void onRmsChanged(float v) {}

    @Override
    public void onBufferReceived(byte[] bytes) {}

    @Override
    public void onEndOfSpeech() {}

    @Override
    public void onError(int i) {}

    @Override
    public void onResults(Bundle bundle) {
        //Getting matches
        ArrayList<String> matches = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

        if (matches != null) {
            //Displaying the first match
            resultText.setText(resultText.getText() + " " + matches.get(0));
            resultText.setMovementMethod(new ScrollingMovementMethod());
            resultText.setSelection(resultText.getText().length());
            while (resultText.canScrollVertically(1)) {
                resultText.scrollBy(0, 10);
            }
        }
    }

    @Override
    public void onPartialResults(Bundle bundle) {}

    @Override
    public void onEvent(int i, Bundle bundle) {}

});

speechBtn:

//Setting up speechBtn states
findViewById(R.id.speechBtn).setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        switch (motionEvent.getAction()) {

            //User stops touching the button.
            case MotionEvent.ACTION_UP:
                mSpeechRecognizer.stopListening();
                break;

            //User touches the button.
            case MotionEvent.ACTION_DOWN:
                try {
                    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                } catch (Exception e){
                    //In case speech is not supported
                    Toast.makeText(getApplicationContext(), "Your device does not support Speech Input", Toast.LENGTH_LONG).show();
                }
                break;

        }
        return false;
    }
});

我试图找到以前做过的类似事情,但是我不走运,而且我不知道如何进行。

0 个答案:

没有答案