安卓 百度语音识别

Android 百度语音识别集成,非常简单
1.最近做一个语音识别的项目,网上找了个demo,很简单,直接调用这个类就可以,做个记录,方便以后用!

public class OnLineUtils implements EventListener {

private EventManager asr;
private OnLineCallBack onLineCallBack;

public OnLineUtils (Context context, OnLineCallBack onLineCallBack){
    asr = EventManagerFactory.create(context,"asr");
    asr.registerListener(this);

    this.onLineCallBack = onLineCallBack;
    initPermission(context);
}

/*
 * android 6.0 以上需要动态申请权限
 */
private void initPermission(Context context) {
    String permissions[] = {Manifest.permission.RECORD_AUDIO,
            Manifest.permission.ACCESS_NETWORK_STATE,
            Manifest.permission.INTERNET,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };

    ArrayList toApplyList = new ArrayList();

    for (String perm : permissions) {
        if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, perm)) {
            toApplyList.add(perm);
            // 进入到这里代表没有权限.

        }
    }
    String tmpList[] = new String[toApplyList.size()];
    if (!toApplyList.isEmpty()) {
        ActivityCompat.requestPermissions((Activity) context, toApplyList.toArray(tmpList), 123);
    }

}


@Override
public void onEvent(String name, String params, byte[] data, int offset, int length) {
    if (params != null && !params.isEmpty()) {

        if (name.equals(SpeechConstant.CALLBACK_EVENT_ASR_PARTIAL)) {

            try {
                JSONObject jsonObject = new JSONObject(params);
                String resultType = jsonObject.getString("result_type");
                if (resultType.equals("final_result")){
                    String finalResult = jsonObject.getString("best_result");

                    onLineCallBack.onSuccess(finalResult);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

}

public interface OnLineCallBack{
    void onSuccess(String result);
}

/**
 * 开始识别
 */
public void start(){
    Map params = new LinkedHashMap<>();
    String event = SpeechConstant.ASR_START;

    params.put(SpeechConstant.ACCEPT_AUDIO_VOLUME,false);
    String json = new JSONObject(params).toString();

    asr.send(event,json,null,0,0);
}

/**
 * 停止识别
 */
public void stop() {
    asr.send(SpeechConstant.ASR_STOP,null,null,0,0);
}

}

你可能感兴趣的:(android)