简体   繁体   English

没有弹出的Android语音识别应用程序

[英]Android speech Recognition App Without Pop Up

I'm currently looking into getting a career with JAVA and have decided to start by building an app. 我目前正在寻找JAVA的职业生涯,并决定从构建应用程序开始。 I have this code right here that I am using to trigger Speech Recognition. 我在这里有这个代码,我用它来触发语音识别。

public class MainActivity extends Activity implements OnClickListener{

private static final int VR_REQUEST = 999;
private ListView wordList;
private final String LOG_TAG = "SpeechRepeatActivity";  
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button speechBtn = (Button) findViewById(R.id.speech_btn);
    wordList = (ListView) findViewById (R.id.word_list);
    PackageManager packManager= getPackageManager();
    List<ResolveInfo> intActivities = packManager.queryIntentActivities
                    (new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    if (intActivities.size() !=0){
        speechBtn.setOnClickListener(this);
    } else {
        speechBtn.setEnabled(false);
        Toast.makeText(this,"Oops - Speech Recognition Not Supported!", 
                                             Toast.LENGTH_LONG).show();
        }       
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
public void onClick(View v){
   if (v.getId() == R.id.speech_btn) {
    listenToSpeech();
   }
}
    private void listenToSpeech() {
    //start the speech recognition intent passing required data
    Intent listenIntent = 
                     new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    //indicate package
    listenIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                        getClass().getPackage().getName());
    //message to display while listening
    listenIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word!");
    //set speech model
    listenIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
                                 RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    //specify number of results to retrieve
    listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
    //start listening
    startActivityForResult(listenIntent, VR_REQUEST);
}
    @Override
    protected void onActivityResult(int requestCode, 
                                             int resultCode, Intent data) {
        //check speech recognition result 
        if (requestCode == VR_REQUEST && resultCode == RESULT_OK) {
    //store the returned word list as an ArrayList
    ArrayList<String> suggestedWords = data.
                     getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
    //set the retrieved list to display in the ListView 
            //using an ArrayAdapter
    wordList.setAdapter(new ArrayAdapter<String> 
                                       (this, R.layout.word, suggestedWords));
}
    //this detects which one the user clicks 
    wordList.setOnItemClickListener(new OnItemClickListener(){
        //click listener for items within list
        public void onItemClick(AdapterView<?> parent, 
                                           View view, int position, long id){
        //cast the 
        TextView wordView = (TextView)
        //retrive the chosen word
        String wordChosen= (String) wordView.
        //output for debugging
        Log.v(LOG_TAG, "chosen:" +wordChosen);
     }});
        super.onActivityResult(requestCode, resultCode, data);
  }
}

In this app the user presses a button and gets displayed with the Google Voice Input screen where you can click a button (it actually goes automatically) and you can speak, it will stop and it will display it. 在这个应用程序中,用户按下一个按钮并显示在Google语音输入屏幕上,您可以在其中单击一个按钮(它实际上自动进入),您可以说话,它将停止并显示它。 I don't want that window to pop up at all though. 我不希望那个窗口弹出来。 Instead just let the user click the button and be able to speak and let the app stop and display the text automatically (it already does that). 相反,只需让用户点击按钮,然后让应用停止并自动显示文本(它已经这样做了)。

PLEASE! 请! I understand that there are already answers on the form showing how to do this, in fact a user name JEEZ posted some code right here . 我知道表格上已有答案显示如何执行此操作,实际上用户名JEEZ在此处发布了一些代码

I don't know if I understood where to put this in my project file. 我不知道我是否理解将其放在项目文件中的位置。 I AM A NOOB! 我是一个NOOB! If anyone could help clarify this I would GREATLY appreciate your help. 如果有人可以帮助澄清这一点,我将非常感谢您的帮助。

Here is my code: 这是我的代码:

package com.example.speechrecognizertest;

import android.os.Bundle;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

private static final int VR_REQUEST = 999;
public static final String TAG = null;
private ListView wordList;
private final String LOG_TAG = "SpeechRepeatActivity";
private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent; 
private boolean mIslistening; 

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button speechBtn = (Button) findViewById(R.id.speech_btn);
    wordList = (ListView) findViewById(R.id.word_list);
    PackageManager packManager = getPackageManager();
    List<ResolveInfo> intActivities = packManager.queryIntentActivities(
            new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
    mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                     this.getPackageName());
    if (!mIslistening)
    {
        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
    } else {
        speechBtn.setEnabled(false);
        Toast.makeText(this, "Oops - Speech Recognition Not Supported!",
                Toast.LENGTH_LONG).show();
    }
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}



protected class SpeechRecognitionListener implements RecognitionListener
{

    @Override
    public void onBeginningOfSpeech()
    {               
        //Log.d(TAG, "onBeginingOfSpeech"); 
    }

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

    }

    @Override
    public void onEndOfSpeech()
    {
        //Log.d(TAG, "onEndOfSpeech");
     }

    @Override
    public void onError(int error)
    {
         mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

        //Log.d(TAG, "error = " + error);
    }

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

    }

    @Override
    public void onPartialResults(Bundle partialResults)
    {

    }

    @Override
    public void onReadyForSpeech(Bundle params)
    {
        Log.d(TAG, "OnReadyForSpeech"); //$NON-NLS-1$
    }

    @Override
    public void onResults(Bundle results)
    {
        //Log.d(TAG, "onResults"); //$NON-NLS-1$
        ArrayList<String> suggestedWords =      results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        // matches are the return values of speech recognition engine
        // Use these values for whatever you wish to do

        wordList.setAdapter(new ArrayAdapter<String>(this, R.layout.word, suggestedWords));



    }

    @Override
    public void onRmsChanged(float rmsdB)
    {

    }

}

AndroidManifest.xml

Add the following permission: 添加以下权限:

<uses-permission android:name="android.permission.RECORD_AUDIO" />

class members 班级成员

private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent; 
private boolean mIslistening; 

In onCreate 在onCreate

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    .........
    .........
    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
    mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                     this.getPackageName());


    SpeechRecognitionListener listener = new SpeechRecognitionListener();
    mSpeechRecognizer.setRecognitionListener(listener);

}   

in your button listener just use this code 在你的按钮监听器中使用此代码

if (!mIsListening)
{
    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}

In onDestroy 在onDestroy中

if (mSpeechRecognizer != null)
{
        mSpeechRecognizer.destroy();
}

Inside your activity create the inner class 在您的活动中创建内部类

protected class SpeechRecognitionListener implements RecognitionListener
{

    @Override
    public void onBeginningOfSpeech()
    {               
        //Log.d(TAG, "onBeginingOfSpeech"); 
    }

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

    }

    @Override
    public void onEndOfSpeech()
    {
        //Log.d(TAG, "onEndOfSpeech");
     }

    @Override
    public void onError(int error)
    {
         mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

        //Log.d(TAG, "error = " + error);
    }

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

    }

    @Override
    public void onPartialResults(Bundle partialResults)
    {

    }

    @Override
    public void onReadyForSpeech(Bundle params)
    {
        Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
    }

    @Override
    public void onResults(Bundle results)
    {
        //Log.d(TAG, "onResults"); //$NON-NLS-1$
        ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        // matches are the return values of speech recognition engine
        // Use these values for whatever you wish to do
    }

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

EDIT 2015-02-07: Incorporated code from the answers to this question by ZakiMak and Born To Win into the code in this answer to make this one more complete. 编辑2015-02-07:由ZakiMakBorn To这个问题的答案中的代码组成的代码在这个答案中使这个更完整。

It's been a long time since the post. 这篇帖子已经很久了。 Still for those who are looking, the above code provided by Hoan is almost complete, but there is an important line missing. 仍然对于那些正在寻找的人来说,Hoan提供的上述代码几乎已经完成,但缺少一条重要的路线。 Both in question and answer and I am not sure how it could work without that. 问题和答案都是如此,我不确定如果没有它可以如何工作。

You need to create the SpeechRecognitionListener and set it as a listener for the SpeechRecognizer. 您需要创建SpeechRecognitionListener并将其设置为SpeechRecognizer的侦听器。 Also it has to be done before we make a call to startListening() method of the SpeechRecognizer. 在我们调用SpeechRecognizer的startListening()方法之前,还必须完成它。

SpeechRecognitionListener listener = new SpeechRecognitionListener(); SpeechRecognitionListener listener = new SpeechRecognitionListener(); mSpeechRecognizer.setRecognitionListener(listener); mSpeechRecognizer.setRecognitionListener(收听);

Then you also need to remove the listener from the onError event. 然后,您还需要从onError事件中删除侦听器。

不要忘记添加以下权限: -

<uses-permission android:name="android.permission.RECORD_AUDIO" />

I ran into that issue as well. 我也遇到了这个问题。 It seems like having startActivityForResult(...) will enable the pop-up mic, then you can handle the response in onActivityResult() . 似乎有startActivityForResult(...)将启用弹出式麦克风,然后您可以在onActivityResult()处理响应。 However, simply adding that startActivityForResult messed up my startListening(mSpeechRecognizerIntent) , so you may need to do more adjustment. 但是,只需添加startActivityForResult搞砸了我的startListening(mSpeechRecognizerIntent) ,因此您可能需要进行更多调整。

mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                                     RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                                     this.getPackageName());
startActivityForResult(recognizerIntent, 100);

// call back
onActivityResult(int requestCode, int resultCode, Intent data){...}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM