Руководство по использованию распознавателя речи - PullRequest
0 голосов
/ 11 января 2019

Я использую следующее руководство "https://www.youtube.com/watch?v=AnNJPf-4T70&index=13&t=0s&list=LLWs2Xlax6q42i66xW1W7F3Q", чтобы попытаться разработать демонстрационное приложение, чтобы я мог ознакомиться с использованием распознавателя речи в реальном приложении и узнать, как разработать приложение, которым можно управлять с помощью голоса разрешить людям с нарушениями моторики использовать все мои приложения, которые я создаю в будущем.

Я заинтересован в использовании намерений использовать тестовое приложение, например, открыть браузер в качестве образца, но я сопоставил код и столкнулся с ошибкой, решение которой не могу найти.

Вот моя деятельность xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blind Accessibility Demo"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        app:srcCompat="@drawable/ic_mic_black_24dp"
        android:layout_alignParentBottom="true"
        android:layout_margin="16dp" />


</RelativeLayout>

Below is my Main activity class

package com.example.ricardo.voicecontrol;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    //    this initalizes the text to speech variable
    private TextToSpeech myTTS;
    //this initalizes the speech reconizer variable
    private SpeechRecognizer speechtest;
private  FloatingActionButton fab;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
               intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                       RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
               intent.putExtra((RecognizerIntent.EXTRA_MAX_RESULTS),1);
               speechtest.startListening(intent);


            }
        });
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//this initalizes text to speech
        initializeTextToSpeech();

//        this code initalizses or "starts" the speech recognizer
        initializeSpeechRecognizer();

    }


    private void initializeSpeechRecognizer() {
        if (SpeechRecognizer.isRecognitionAvailable((this))
                ) {
            speechtest = SpeechRecognizer.createSpeechRecognizer(this);
            speechtest.setRecognitionListener(new RecognitionListener() {
                @Override
                public void onReadyForSpeech(Bundle params) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float rmsdB) {

                }

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

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int error) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    List<String> results = bundle.getStringArrayList(
                            (
                                    SpeechRecognizer.RESULTS_RECOGNITION
                            ));
                    processResults(results.get(0));

                }

                @Override
                public void onPartialResults(Bundle partialResults) {

                }

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

                }
            });
        }
    }

    private void processResults(String command) {
        command = command.toLowerCase();
        if (command.indexOf("open") != -1) {
            if (command.indexOf("browser") != -1) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.yahoo.com/"));
                startActivity(intent);
            }
        }

}
//        what is your name
//    what is the time





    private void initializeTextToSpeech() {
        myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (myTTS.getEngines().size() == 0) {
                    Toast.makeText(MainActivity.this, "There is no text to speech engine available on your phone"
                            , Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    myTTS.setLanguage(Locale.US);
//                    this line of code below will be spoken once the app loads up
                    speak("This app can be controlled using your voice tap the microphone icon to begin");
                }
            }
        });
    }

    private void speak(String message) {
        if (Build.VERSION.SDK_INT >= 21) {
            myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null, null);
        } else {
            myTTS.speak(message, TextToSpeech.QUEUE_FLUSH, null);
        }

        }
    @Override
    protected void onPause () {
        super.onPause();
        myTTS.shutdown();
    }

    private class FloatingActionButton {
        public void setOnClickListener(View.OnClickListener onClickListener) {
        }
    }
}

Ошибка, которую я получаю: «Необратимые типы; невозможно преобразовать в android.viewView в com.example.ricardo.voicecontrol.MainActivity.FloatingActionButton ''". Я попытался переименовать файл и сделать недействительными деньги и перезапустить, но не нашел изменений.

1 Ответ

0 голосов
/ 11 января 2019

Похоже, что ваш FloatingActionButton не является View, вы создаете внутренний класс

private class FloatingActionButton {
    public void setOnClickListener(View.OnClickListener onClickListener) {
    }
}

Этого не должно быть вообще. Вы создали класс, который не расширяет View, и попытались использовать его в качестве View. Выньте этот класс и используйте FloatingActionButton из библиотеки. Это основная причина вашей ошибки.

Попробуйте изменить

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
           intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                   RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
           intent.putExtra((RecognizerIntent.EXTRA_MAX_RESULTS),1);
           speechtest.startListening(intent);


        }
    });
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

К

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
           Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
           intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                   RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
           intent.putExtra((RecognizerIntent.EXTRA_MAX_RESULTS),1);
           speechtest.startListening(intent);


        }
    });

Я ожидаю, что вы получите исключение NullPointerException.

Эта строка кода

 setContentView(R.layout.activity_main);

Говорит; загрузите мой xml-файл Activity_main в качестве текущего макета для этого действия.

И эта строка кода

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

Говорит; В XML-файле, который я загрузил с помощью setContentView, найдите представление с идентификатором fab и приведите его к FloatingActionButton

Так как ваш код выложен, вы пытаетесь найти представление до его загрузки.

...