【问题标题】:Android speech Recognition App Without Pop Up无弹窗的安卓语音识别App
【发布时间】:2013-04-26 04:32:59
【问题描述】:

我目前正在寻找从事 JAVA 的职业,并决定从构建应用程序开始。 我在这里有这段代码,我用它来触发语音识别。

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);
  }
}

在这个应用程序中,用户按下一个按钮并显示在 Google 语音输入屏幕上,您可以在其中单击一个按钮(它实际上是自动运行的)并且您可以说话,它会停止并显示它。我根本不希望那个窗口弹出。相反,只需让用户单击按钮并能够说话,让应用停止并自动显示文本(它已经这样做了)。

请!我知道表单上已经有显示如何执行此操作的答案,实际上是用户名 JEEZ 发布了some code right here

我不知道我是否理解将它放在我的项目文件中的哪个位置。我是菜鸟!如果有人可以帮助澄清这一点,我将非常感谢您的帮助。

这是我的代码:

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)
    {

    }

}

【问题讨论】:

  • 谢谢 Hoan,只有一个问题。我看到了您从该教程中引用的代码,但我不知道如何将其合并到我的项目中。你能帮忙吗?
  • 你使用activity对吗?
  • 我不确定你的意思。我已经在主文档中发布了我的所有代码。活动(我认为这意味着布局)有一个按钮和一个列表视图。除此之外,所有内容都显示在问题上。 (我真的希望我能回答你的问题)。在这里只是一个编辑-我不使用我不相信的活动,因为它从未被调用过。所有这些都属于代码主要活动。我将如何使用该活动?我为什么要使用它,它将为我做什么?非常感谢您的快速回复!
  • 嗨,霍恩!我想在你的帖子中发表评论,但由于某种原因,我认为我也不允许...... :(。你给我的东西非常有帮助。我认为我遇到的主要问题是我没有不知道用什么替换。我理解前三个步骤,但不明白 onDestroy 是什么以及是否应该用某些东西替换类。非常完整的答案,非常感谢!另外,我知道你显然是专业人士,我很想努力赶上你的水平。如果你能提出任何建议来帮助我学习,那将非常有帮助!

标签: java android voice-recognition


【解决方案1】:

AndroidManifest.xml

添加以下权限:

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

班级成员

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

在 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);

}   

在您的按钮监听器中使用此代码

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

在 onDestroy 中

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

在你的活动中创建内部类

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)
    {
    }
}

编辑 2015-02-07:将 ZakiMakBorn To Win 对此问题的答案中的代码合并到此答案中的代码中,以使其更加完整。

【讨论】:

  • 以上内容转到您的 MainActivity
  • 当我调用 mSpeechRecognizer.startListening(mSpeechRecognizerIntent);什么都没有发生,它从来没有说它已经准备好讲话了......
  • 我在这里遇到了问题。最后,我将数组列表转换为字符串并将该字符串设置为 TextView ...问题是实际上没有显示任何文本。关于如何发生这种情况的任何想法?
  • logcat 是否显示您设置为 TextView 的字符串?
  • 在 Android 6+ 上,RECORD_AUDIO 权限是危险的权限之一,这意味着您需要让用户确认才能真正获得它。当您在开发应用程序并使用 ADB 进行调试时,可能不会提示您批准“危险”的录制音频(麦克风)权限,因此您需要在设备上手动打开设置中的应用程序并授予权限。
【解决方案2】:

别忘了添加以下权限:-

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

【讨论】:

    【解决方案3】:

    这篇文章已经很久了。对于那些正在寻找的人来说,Hoan 提供的上述代码几乎是完整的,但是缺少一个重要的行。在问题和答案中,我不确定没有它如何工作。

    您需要创建 SpeechRecognitionListener 并将其设置为 SpeechRecognizer 的侦听器。此外,它必须在我们调用 SpeechRecognizer 的 startListening() 方法之前完成。

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

    那么你还需要从 onError 事件中移除监听器。

    【讨论】:

      【解决方案4】:

      我也遇到了这个问题。似乎拥有startActivityForResult(...) 将启用弹出式麦克风,然后您可以处理onActivityResult() 中的响应。但是,简单地添加 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){...}
      

      【讨论】:

        猜你喜欢
        • 2011-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多