无需 Google 对话框的语音识别

2024-02-16

我将尝试使用带有 RecognitionListener 的语音识别,无需 Google 对话框 但不起作用,启动应用程序时只会发出蜂鸣声。我已将音频记录和互联网权限添加到清单文件中。我希望你告诉我并帮助我找到错误...我在 Log cat 上没有错误...我想要在用户打招呼时进行循环,Toast 显示一条消息“识别正常”,并且列表视图显示结果。

 public  class MainActivity extends Activity  implements RecognitionListener
{

 private ListView wordsList;

private SpeechRecognizer mSpeechRecognizer;
private Intent mSpeechRecognizerIntent; 


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

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

    wordsList = (ListView) findViewById(R.id.listView1); 

    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

}


    public void onBeginningOfSpeech(){ }

        public void onBufferReceived(byte[] buffer){ }

        public void onEndOfSpeech(){ }

        public void onError(int error){

           //mSpeechRecognizer.startListening(mSpeechRecognizerIntent);

    }

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


    public void onPartialResults(Bundle partialResults){ }


    public void onReadyForSpeech(Bundle params){


        Toast.makeText(getBaseContext(), "Voice recording starts", Toast.LENGTH_SHORT).show();

    }

    public void onResults(Bundle results)
    {

        ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);


        wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,  matches));


        if ( matches.contains("hello") {

            Toast.makeText(getBaseContext(), "Recognision OK!!!", Toast.LENGTH_SHORT).show();

          }

    }

    public void onRmsChanged(float rmsdB) { }

  }

试试这个代码

import java.util.ArrayList;

import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

public class VoiceRecognitionActivity extends Activity implements RecognitionListener {

    private TextView returnedText;
    private ToggleButton toggleButton;
    private ProgressBar progressBar;
    private SpeechRecognizer speech = null;
    private Intent recognizerIntent;
    private String LOG_TAG = "VoiceRecognitionActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_recognition);
        returnedText = (TextView) findViewById(R.id.textView1);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);

        progressBar.setVisibility(View.INVISIBLE);
        speech = SpeechRecognizer.createSpeechRecognizer(this);
        speech.setRecognitionListener(this);
        recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,"en");
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,this.getPackageName());

recognizerIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3);

        toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                if (isChecked) {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setIndeterminate(true);
                    speech.startListening(recognizerIntent);
                } else {
                    progressBar.setIndeterminate(false);
                    progressBar.setVisibility(View.INVISIBLE);
                    speech.stopListening();
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (speech != null) {
            speech.destroy();
            Log.i(LOG_TAG, "destroy");
        }

    }

    @Override
    public void onBeginningOfSpeech() {
        Log.i(LOG_TAG, "onBeginningOfSpeech");
        progressBar.setIndeterminate(false);
        progressBar.setMax(10);
    }

    @Override
    public void onBufferReceived(byte[] buffer) {
        Log.i(LOG_TAG, "onBufferReceived: " + buffer);
    }

    @Override
    public void onEndOfSpeech() {
        Log.i(LOG_TAG, "onEndOfSpeech");
        progressBar.setIndeterminate(true);
        toggleButton.setChecked(false);
    }

    @Override
    public void onError(int errorCode) {
        String errorMessage = getErrorText(errorCode);
        Log.d(LOG_TAG, "FAILED " + errorMessage);
        returnedText.setText(errorMessage);
        toggleButton.setChecked(false);
    }

    @Override
    public void onEvent(int arg0, Bundle arg1) {
        Log.i(LOG_TAG, "onEvent");
    }

    @Override
    public void onPartialResults(Bundle arg0) {
        Log.i(LOG_TAG, "onPartialResults");
    }

    @Override
    public void onReadyForSpeech(Bundle arg0) {
        Log.i(LOG_TAG, "onReadyForSpeech");
    }

    @Override
    public void onResults(Bundle results) {
        Log.i(LOG_TAG, "onResults");
        ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        String text = "";
        for (String result : matches)
            text += result + "\n";

        returnedText.setText(text);
    }

    @Override
    public void onRmsChanged(float rmsdB) {
        Log.i(LOG_TAG, "onRmsChanged: " + rmsdB);
        progressBar.setProgress((int) rmsdB);
    }

    public static String getErrorText(int errorCode) {
        String message;
        switch (errorCode) {
        case SpeechRecognizer.ERROR_AUDIO:
            message = "Audio recording error";
            break;
        case SpeechRecognizer.ERROR_CLIENT:
            message = "Client side error";
            break;
        case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
            message = "Insufficient permissions";
            break;
        case SpeechRecognizer.ERROR_NETWORK:
            message = "Network error";
            break;
        case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
            message = "Network timeout";
            break;
        case SpeechRecognizer.ERROR_NO_MATCH:
            message = "No match";
            break;
        case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
            message = "RecognitionService busy";
            break;
        case SpeechRecognizer.ERROR_SERVER:
            message = "error from server";
            break;
        case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
            message = "No speech input";
            break;
        default:
            message = "Didn't understand, please try again.";
            break;
        }
        return message;
    }

}

Activity_voice_recognition.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/toggleButton1"
        android:layout_marginTop="28dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/progressBar1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="47dp" />

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:text="ToggleButton" />

</RelativeLayout>

AndroidManifest.xml

<manifest 
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakesh.voicerecognitionexample"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".VoiceRecognitionActivity"
            android:label="@string/title_activity_voice_recognition" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无需 Google 对话框的语音识别 的相关文章

随机推荐

  • 仅重置 div 的 css 样式

    嗯 我有一个很大的 html 文档 我想将控件嵌入到该文档中 但该控件的 css 样式与大 html 文档的样式重叠 如何重置仅 div 以及所有嵌套 div 的所有样式 随着雅虎重置http yuilibrary com yui docs
  • django:使用一对一扩展用户模型:如何保存()配置文件模型的字段

    我有一个基本的 Django 应用程序 其中除了用户模型之外 我还使用扩展了配置文件模型一对一字段 模型 py class Profile models Model user models OneToOneField User on del
  • 在 info.plist 文件中设置 SceneDelegate

    我有一个应用程序目标和一些静态库 由于某些原因 我将 SceneDelegate 从应用程序目标移至静态库之一 在info plist文件中 SceneDelegate设置为 PRODUCT MODULE NAME SceneDelegat
  • Android Studio StackOverFlowError:null

    今天更新到 2 3 版本后 我的 Android Studio 停止工作了 null java lang StackOverflowError at java lang ClassLoader defineClass1 Native Met
  • 执行 WebAPI 2 JSON Post 时未找到 HttpRequestBase.GetBufferedInputStream

    使用 Visual Studio 创建 MVC5 WebAPI2 项目 创建了一个基本的 JSON POST 发布参数导致 HttpRequestBase GetBufferedInputStream 未找到失败 适用于 带有视觉工作室的W
  • Spark 文件流获取文件名

    我需要知道从输入目录流式传输的输入文件的文件名 下面是scala编程中的spark FileStreaming代码 object FileStreamExample def main args Array String Unit val s
  • wcf REST 服务和 JQuery Ajax Post:不允许方法

    有人知道这是怎么回事吗 我无法从 WCF Rest 服务获取 json 响应 Jquery ajax type POST url http localhost 8090 UserService ValidateUser data usern
  • 无法从 Spring Cloud Config Server 获取值到我的 Config-Client(limits-service)

    经过几天的互联网搜索和多次尝试 对我来说没有任何结果 我在这里写下 我有项目 弹簧云配置服务器其中包含以下文件 可以从以下位置访问完整项目https github com AshishBharadwaj94 spring cloud con
  • 线程的垃圾收集

    我需要保护吗Thread来自垃圾收集器的对象 那么包含线程运行的函数的对象呢 考虑这个简单的服务器 class Server readonly TcpClient client public Server TcpClient client
  • Node.js Express socket.io 端口 3000 正在使用

    我一直在关注这个 http socket io get started chat http socket io get started chat 有关如何使用 socket io 制作简单聊天应用程序的教程 然而 我尝试使用 Express
  • Xcode 构建时错误:“无法加载文件列表的内容:‘.../Info.plist’(在目标‘xxxx’中)

    Xcode 今天开始在项目中抛出此错误 我无法弄清楚它的含义以及如何对其进行故障排除 并且它不会出现在任何搜索中 它在尝试构建到设备后立即发生 没有编译脚本等 错误 无法加载文件列表的内容 Users Products Debug appl
  • 如何将字符串长度转换为像素单位?

    我有一个像这样的字符串 string s This is my string 我正在创建 Telerik 报告 我需要定义一个textbox这就是我的绳子的宽度 但是 大小属性需要设置为单位 像素 点 英寸等 如何将字符串长度转换为像素 以
  • C++ 中整数的幂[重复]

    这个问题在这里已经有答案了 我需要得到结果pow a b 作为整数 a 和 b 也是整数 目前 计算中 int pow double a double b 包含错误 一个函数可以是什么 它可以对整数执行 pow a b 并返回一个整数 但奇
  • 我可以在 C# 中将 json 反序列化为匿名类型吗?

    我从数据库中读取了一个很长的json 我只想要该 json 的一个属性 我有两个选择 A 为该 json 创建一个接口并反序列化到该接口 这是否有点矫枉过正 因为我只需要一个属性 b 找到我需要的子字符串 正则表达式 哪一个是首选 更新 我
  • 在 C++0x 中传递/移动构造函数的参数

    如果我有一个带有 n 个参数的构造函数 那么该构造函数的任何参数都可以是右值和左值 是否可以通过右值的移动语义来支持这一点 而无需为每个可能的右值 左值组合编写 2 n 构造函数 你可以按值来获取每一项 如下所示 struct foo fo
  • 如何在 Jenkins 中手动安装插件

    从更新中心安装插件会导致 检查互联网连接 无法连接到http www google com http www google com 也许您需要配置 HTTP 代理 部署插件失败 详细信息 hudson util IOException2 无
  • 使用 HtmlService HtmlTemplate 时设置 Google Apps 脚本 showModalDialog 的高度

    我目前正在将使用已弃用的 UI 服务的 Google Apps 脚本更改为 HtmlService 我使用以下代码创建了一个模式对话 在电子表格容器绑定脚本中 var htmlTemplate HtmlService createTempl
  • Angular 导出 Excel 客户端

    我正在使用 Angular v4 我想如何从组件中的对象开始构建 Excel 电子表格 我需要点击按钮下载 Excel 文件 并且我必须在客户端执行此操作 我有一个由数组组成的 json 文件 我需要将其传输到 Excel 文件上 可能可以
  • Strapi v4:填充时没有关系字段

    我正在尝试使用关系名称填充特定关系 categories 与 populate 参数结合使用 但它不会填充categories 当我查看架构时 我发现关系字段存在于属性对象中 但我的回复中仍然只得到非关系字段 我尝试了上面提到的所有组合St
  • 无需 Google 对话框的语音识别

    我将尝试使用带有 RecognitionListener 的语音识别 无需 Google 对话框 但不起作用 启动应用程序时只会发出蜂鸣声 我已将音频记录和互联网权限添加到清单文件中 我希望你告诉我并帮助我找到错误 我在 Log cat 上