如何在方法中返回SpeechRecognizer的结果?

时间:2016-05-16 05:49:23

标签: android speech-to-text

我正在制作一个语音到文本的Android应用程序,我在这里附加了源代码。我的问题是,我已经使用SpeechRecognizer类成功地将语音转换为文本。但是当我调用SpeechToText类的getResult()方法时,它会给出

java.lang.NullPointerException Attempt to invoke virtual method java.lang.Object java.util.ArrayList.get(int) on a null object reference

错误的原因是最初"结果"为ArrayList为空,并在调用onResults()方法时进行初始化。由于在getResult()之前调用了onResults()方法,因此ArrayList结果为 null 。所以它给出了错误。但我希望getResult()方法返回存储在ArrayList结果中的结果。怎么做?顺便说一句,如果我保持返回类型getResult() void,那么代码运行正确并提供输出。但我想从getResult()返回输出而不是烘烤它。

请帮助.......

SpeechToText.java:

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.widget.Toast;

public class SpeechToText{

private Context context;
private Intent intent;
private SpeechRecognizer recognizer;
private ArrayList<String> results;

public SpeechToText(Context c){
    this.context = c;

    intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);

    RecognitionListener listener = new RecognitionListener() {
        @Override
        public void onResults(Bundle resultBundle) {
            results = new ArrayList(resultBundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION));
            Toast.makeText(context, results.get(0), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onReadyForSpeech(Bundle params) {}

        @Override
        public void onError(int error) {}

        @Override
        public void onBeginningOfSpeech() {}

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

        @Override
        public void onEndOfSpeech() {}

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

        @Override
        public void onPartialResults(Bundle partialResults) {}

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

    recognizer = SpeechRecognizer.createSpeechRecognizer(context);
    recognizer.setRecognitionListener(listener);
}

public String getResult(){
    recognizer.startListening(intent);
    return results.get(0);
}

}

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    Button btn;
    SpeechToText stt;

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

        stt = new SpeechToText(this);

        btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), stt.getResult(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

0 个答案:

没有答案