栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android 调用谷歌原生语音识别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android 调用谷歌原生语音识别

前提:

1.安装谷歌语音搜索APP

2.需要越狱连接外网

废话不多说,直接上代码

  public void onClick(View v) {
                //开启语音识别功能
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                //设置模式,这里设置成自由模式
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                //提示语音开始文字
                intent.putExtra(RecognizerIntent.EXTRA_prompt,"Please start your voice");
                //开始进行语音识别,这里先检测手机(模拟器)是否支持语音识别并且捕获异常
                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });

使用onActivityResult接收返回的结果

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_SPEECH: {
                if (resultCode == RESULT_OK && data != null) {
                    ArrayList text = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    //这里集合列表中第一个值为匹配度最高的值
                    txtText.setText(text.get(0));
                }
                break;
            }
        }
    }
 

布局文件


    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@+id/txtText"
    android:gravity="center"
    android:orientation="vertical">

            android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:hint="@string/edit"/>

            android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now"/>


 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/332725.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号