Android Google原生语音识别

1.调用Google原生语音识别

 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); //RESULT_SPEECH为Activity回调时的code值
        } catch (ActivityNotFoundException a) { //当前设备无法支持google语音识别
            Toast t = Toast.makeText(getApplicationContext(),
                    "Opps! Your device doesn't support Speech to Text",
                    Toast.LENGTH_SHORT);
            t.show();
        }

2.Activity回调结果

  @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<String> text = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    //此集合列表第一个值为匹配度最高的值
                    tv_open.setText(text.get(0));
                }
                break;
            }

        }
    }

3.由于Google语音识别有一定的限制,所以很多设备可能不支持。但又无法提取获取是否支持此功能,因此提供一个判断此Intent是否可用的方法

 public static boolean isIntentAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);//参数为需要启动Google识别的action,也可动态传递
        List<ResolveInfo> list =
                packageManager.queryIntentActivities(intent,
                        PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

——————————-

三样东西有助于缓解生命的辛劳:希望,睡眠和微笑

发布了20 篇原创文章 · 获赞 2 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览