SpeechCompServiceImpl.java 19.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
package com.wd.speech;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.idst.nui.AsrResult;
import com.alibaba.idst.nui.CommonUtils;
import com.alibaba.idst.nui.Constants;
import com.alibaba.idst.nui.INativeNuiCallback;
import com.alibaba.idst.nui.KwsResult;
import com.alibaba.idst.nui.NativeNui;
import com.wd.speech.dialog.VoiceSearchDialog;
import com.wd.speech.listener.SpeechResultCallback;
import com.wd.base.log.Logger;
import com.wd.common.callback.RouterCallBack;
import com.wd.common.constant.RouterServiceConstants;
import com.wd.common.permissions.IPmsCallBack;
import com.wd.common.permissions.PermissionsUtils;
import com.wd.common.provider.ISpeechProvider;
import com.wd.foundation.wdkitcore.tools.JsonUtils;
import com.wd.foundation.wdkitcore.tools.ResUtils;
import com.wd.foundation.wdkitcore.tools.StringUtils;

import androidx.fragment.app.FragmentActivity;

/**
 * 描述:语音识别
 *
 * @author : lvjinhui
 * @since: 2022/6/21
 */
@Route(path = RouterServiceConstants.PATH_MODULE_SPEECH_SERVICE)
public class SpeechCompServiceImpl implements ISpeechProvider, VoiceSearchDialog.OnDialogClickListener {
    /**
     * 采样率
     */
    public static final int SAMPLE_RATE = 16000;

    private static final int FMAX = 4;

    /**
     * 波浪大小
     */
    public static final int WAVE_FRAM_SIZE = 20 * 2 * 1 * 16000 / 1000;

    private static final String TAG = "SpeechCompService";

    private String requestUrl = "wss://nls-gateway.cn-shanghai.aliyuncs.com:443/ws/v1";

    private NativeNui nuiInstance = new NativeNui();

    private AudioRecord mAudioRecorder;

    private boolean mInit = false;

    private HandlerThread mHandlerThread;

    private Handler mHandler;

    private FragmentActivity mContext;

    private RouterCallBack nuiResultCallBack;

    private VoiceSearchDialog mDialog;

    private boolean haveResult;

    /**
     * 识别开始
     */
    private static final int SPEAK_START = 1000;
    /**
     * 识别中
     */
    private static final int SPEAK_RECOGNIZE = 1001;
    /**
     * 录音出错
     */
    private static final int SPEAK_ERROR = 1002;

    /**
     * 录音暂停
     */
    private static final int SPEAK_STOP = 1003;

    private final Handler mDialogHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SPEAK_START:
                    //开始
                    if (resultCallback != null) {
                        resultCallback.start();
                    }
                    break;
                case SPEAK_RECOGNIZE:
                    if (mDialog != null && mDialog.isShowing()) {
                        String content = (String) msg.obj;
                        int arg1 = msg.arg1;
                        if (arg1 == 2) {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (resultCallback != null) {
                                        resultCallback.result(content);
                                    }
                                    if (nuiResultCallBack != null) {
                                        nuiResultCallBack.onResultCallBack(content);
                                    }
                                    stopSpeech();
                                    haveResult = false;
                                }
                            }, 1000);
                        }
                    }
                    break;
                case SPEAK_ERROR:
                    if (resultCallback != null) {
                        resultCallback.error();
                    }
                    break;
                case SPEAK_STOP:
                    if (resultCallback != null) {
                        resultCallback.stop();
                    }
                    break;
                default:
                    break;
            }
        }
    };



    public INativeNuiCallback iNativeNuiCallback = new INativeNuiCallback() {
        /**
         * EVENT_VAD_START
         * 检测到人声起点
         * EVENT_VAD_END
         * 检测到人声尾点
         * EVENT_ASR_PARTIAL_RESULT
         * 语音识别中间结果
         * EVENT_ASR_RESULT
         * 语音识别最终结果
         * EVENT_ASR_ERROR
         * 根据错误码信息判断出错原因
         * EVENT_MIC_ERROR
         * 录音错误
         */
        @Override
        public void onNuiEventCallback(Constants.NuiEvent event, final int resultCode, final int arg2, KwsResult kwsResult, AsrResult asrResult) {
            Logger.t(TAG).e("onNuiEventCallback>>>>" + event);

            if (event == Constants.NuiEvent.EVENT_VAD_START) {// 检测到人声起点
                Logger.t(TAG).e("onNuiVprEventCallback 检测到人声起点");
            } else if (event == Constants.NuiEvent.EVENT_VAD_END) {// 检测到人声尾点
                Logger.t(TAG).e("onNuiVprEventCallback 检测到人声尾点");
            } else if (event == Constants.NuiEvent.EVENT_ASR_PARTIAL_RESULT) {// 语音识别中间结果
                Logger.t(TAG).e("onNuiVprEventCallback 语音识别中间结果" + asrResult.asrResult);
                convertResult(asrResult.asrResult, event);
            } else if (event == Constants.NuiEvent.EVENT_ASR_RESULT) {// 语音识别最终结果
                Logger.t(TAG).e("onNuiVprEventCallback 语音识别最终结果" + asrResult.asrResult);
                convertResult(asrResult.asrResult, event);
            } else if (event == Constants.NuiEvent.EVENT_ASR_ERROR) {// 根据错误码信息判断出错原因
                Logger.t(TAG).e("onNuiVprEventCallback 根据错误码信息判断出错原因");
                mContext.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                        ToastNightUtil.showShort("ERROR with " + resultCode);
                    }
                });
                sendHandleEmptyMessage(SPEAK_ERROR);
            } else if (event == Constants.NuiEvent.EVENT_MIC_ERROR) {// 录音错误
                Logger.t("ouyang").e("SPEAK_ERROR 录音错误>>>>EVENT_MIC_ERROR");
                sendHandleEmptyMessage(SPEAK_ERROR);
            }
        }

        @Override
        public int onNuiNeedAudioData(byte[] buffer, int len) {
            Logger.t(TAG).i("onNuiNeedAudioData>>>>" + len);
            int ret = 0;
            if (mAudioRecorder.getState() != AudioRecord.STATE_INITIALIZED) {
                return -1;
            }
            ret = mAudioRecorder.read(buffer, 0, len);
            return ret;
        }

        @Override
        public void onNuiAudioStateChanged(Constants.AudioState audioState) {
            Logger.t(TAG).e("onNuiAudioStateChanged>>>>audioState" + audioState);
            if (audioState == Constants.AudioState.STATE_OPEN) {
                try {
                    mAudioRecorder.startRecording();
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else if (audioState == Constants.AudioState.STATE_CLOSE) {
                try {
                    mAudioRecorder.release();
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else if (audioState == Constants.AudioState.STATE_PAUSE) {
                if (!haveResult) {
                    try {
                        mAudioRecorder.stop();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    sendHandleEmptyMessage(SPEAK_STOP);
                }
            }
        }

        @Override
        public void onNuiAudioRMSChanged(float val) {
            Logger.t(TAG).i("onNuiAudioRMSChanged vol " + val);
        }

        @Override
        public void onNuiVprEventCallback(Constants.NuiVprEvent nuiVprEvent) {
            Logger.t(TAG).e("onNuiAudioRMSChanged>>>>" + nuiVprEvent.getCode());
        }

    };

    /**
     * 把返回的Json串转化成文字
     *
     * @param jsonStr
     */
    private void convertResult(String jsonStr, Constants.NuiEvent event) {
        try {
            JSONObject jsonObject = JsonUtils.convertJsonToJsonObject(jsonStr);
            JSONObject payload = jsonObject.getJSONObject("payload");
            if (payload != null) {
                String result = payload.getString("result");
                if (StringUtils.isBlank(result)) {
                    return;
                }

                if (result.length() >= 30) {
                    sendHandleMessage(SPEAK_RECOGNIZE, result, 2);
                    return;
                }


                if (event == Constants.NuiEvent.EVENT_ASR_PARTIAL_RESULT) {
                    // 语音识别中间结果
                    sendHandleMessage(SPEAK_RECOGNIZE, result, 1);
                } else if (event == Constants.NuiEvent.EVENT_ASR_RESULT) {
                    // 语音识别最终结果
                    sendHandleMessage(SPEAK_RECOGNIZE, result, 2);
                }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 对外提供的识别的方法
     */
    @Override
    public void beginSpeech() {
        PermissionsUtils.getRecordAudio(mContext, new IPmsCallBack() {
            @Override
            public void granted() {
                initHandler();
                if (mAudioRecorder==null) {
                    initAudioRecord();
                }
                startDialog();
            }

            @Override
            public void notGranted() {
                // 没有授权,提示下
//                ToastNightUtil.showShort(ResUtils.getString(R.string.record_permissions));
            }
        });

    }

    /**
     * 数据回调监听
     */
    public SpeechResultCallback resultCallback = null;

    public void setResultCallback(SpeechResultCallback callback) {
        this.resultCallback = callback;
    }

    /**
     * 初始化SDK
     * @param accessToken
     * @param context
     * @return
     */
    @Override
    public boolean initSpeechSdk(String accessToken, FragmentActivity context) {
        this.mContext = context;
        return doInit(accessToken);
    }

    /**
     * 内部调用
     *
     * @param assetsPath
     * @param debugPath
     * @param callback
     * @return boolean
     */
    private boolean initSpeech(String assetsPath, String debugPath,String accessToken, INativeNuiCallback callback) {

        int ret = nuiInstance.initialize(callback, genInitParams(assetsPath, debugPath,accessToken),
            Constants.LogLevel.LOG_LEVEL_DEBUG, true);
        if (ret == Constants.NuiResultCode.SUCCESS) {
            mInit = true;
        }
        // 设置相关识别参数,具体参考API文档
        nuiInstance.setParams(genParams());
        return mInit;
    }

    @Override
    public void stopSpeech() {
        dismissDialog();
    }

    @Override
    public void release() {
        if (nuiInstance != null) {
            nuiInstance.release();
        }


        if (mDialog != null) {
            mDialog = null;
        }

        if (mAudioRecorder != null) {
            mAudioRecorder.release();
            mAudioRecorder = null;
        }


        mInit = false;

        if (mHandlerThread != null) {
            mHandlerThread = null;
        }

        if (mHandler != null) {
            mHandler = null;
        }

        if (mContext != null) {
            mContext = null;
        }


        if (nuiResultCallBack != null) {
            nuiResultCallBack = null;
        }

        haveResult = false;
    }

    private void startDialog() {
        showVoiceSearchDialog();
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (nuiInstance != null) {
                    int ret = nuiInstance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams());
                }
            }
        });
    }

    private void showVoiceSearchDialog() {
        if (mContext == null || mContext.isDestroyed() || mContext.isFinishing()) {
            return;
        }
        if (mDialog == null) {
            mDialog = new VoiceSearchDialog(mContext, this);
        }

        if (!mDialog.isShowing()) {
            mDialog.showDefaultHint();
        }

        sendHandleEmptyMessage(SPEAK_START);
    }

    /**
     * 初始化语音搜索弹框
     */
    public void initVoiceSearchDialog(){
        if (mContext == null || mContext.isDestroyed() || mContext.isFinishing()) {
            return;
        }
        /*if (mDialog == null) {
            mDialog = new VoiceSearchDialog(mContext, this);
        }*/

        mDialog = new VoiceSearchDialog(mContext, this,1);

        if (!mDialog.isShowing()) {
            mDialog.showDefaultHint();
        }
    }

    /**
     * handler
     */
    private void initHandler() {
        mHandlerThread = new HandlerThread("process_thread");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
    }

    private boolean doInit(String accessToken) {
        if (mContext == null) {
            return false;
        }
        if (CommonUtils.copyAssetsData(mContext)) {
            Logger.t(TAG).i("copy assets data done");
        } else {
            Logger.t(TAG).i("copy assets failed");
            return false;
        }

        return initSDK(accessToken);
    }

    private boolean initSDK(String accessToken) {
        // 获取工作路径
        String assetsPath = CommonUtils.getModelPath(mContext);
        String debugPath = mContext.getExternalCacheDir().getAbsolutePath() + "/debug_" + SystemClock.uptimeMillis();
        Utils.createDir(debugPath);
        boolean initResult = initSpeech(assetsPath, debugPath, accessToken,iNativeNuiCallback);
        Logger.t(TAG).i("copy assets data done>>>" + initResult);
        return initResult;
    }


    /**
     * 获取录音实例
     */
    @SuppressLint("MissingPermission")
    private void initAudioRecord() {
        // 录音初始化,录音参数中格式只支持16bit/单通道,采样率支持8K/16K
        mAudioRecorder = new AudioRecord(MediaRecorder.AudioSource.CAMCORDER, SAMPLE_RATE, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT, WAVE_FRAM_SIZE * FMAX);
    }

    private String genInitParams(String workpath, String debugpath,String accessToken) {
        String str = "";
        try {
            // Auth实现访问阿里云鉴权SDK动态获取token
            // 通过网络请求,获取Token信息
            JSONObject object = Auth.getNetAliYunTicket(accessToken);
            // token 24小时过期,因此需要通过阿里云SDK来进行更新
            object.put("url", requestUrl);
            object.put("device_id", Utils.getDeviceId());
            object.put("workspace", workpath);
            object.put("debug_path", debugpath);
            object.put("sample_rate", SAMPLE_RATE);
            object.put("format", "opus");
            str = object.toString();
        } catch (JSONException e) {
            Logger.t(TAG).e("genInitParams:" + e.getMessage());
        }

        Logger.t(TAG).i("InsideUserContext:" + str);
        return str;
    }

    private String genParams() {
        String params = "";
        try {
            // 设置参数
            JSONObject nlsConfig = new JSONObject();
            // 是否返回中间识别结果,默认值:False。
            nlsConfig.put("enable_intermediate_result", true);
            // 是否启动语音检测。默认值:False。
            nlsConfig.put("enable_voice_detection", true);
            // 当enable_voice_detection设置为true时,该参数生效。表示允许的最大开始静音时长。单位:毫秒。超出后(即开始识别后多长时间没有检测到声音)服务端将会发送TaskFailed事件,结束本次识别。
            nlsConfig.put("max_start_silence", 6000);
            /**
             * 当enable_voice_detection设置为true时,该参数生效。
             * 表示允许的最大结束静音时长。
             * 单位:毫秒,取值范围:200ms~6000ms。
             * 超出时长服务端会发送RecognitionCompleted事件,结束本次识别(需要注意后续的语音将不会进行识别)。
             */
            nlsConfig.put("max_end_silence", 6000);
            JSONObject tmp = new JSONObject();
            tmp.put("nls_config", nlsConfig);
            tmp.put("service_type", Constants.kServiceTypeASR);
            params = tmp.toString();
        } catch (JSONException e) {
            Logger.t(TAG).e("genParams:" + e.getMessage());
        }
        return params;
    }

    private String genDialogParams() {
        String params = "";
        try {
            JSONObject dialogParam = new JSONObject();
            params = dialogParam.toString();
        } catch (JSONException e) {
            Logger.t(TAG).e("genDialogParams:" + e.getMessage());
        }

        Logger.t(TAG).i("dialog params: " + params);
        return params;
    }


    private void sendHandleEmptyMessage(int what) {
        Message message = mDialogHandler.obtainMessage();
        message.what = what;
        message.sendToTarget();
    }

    /**
     * @param what
     * @param result
     * @param resultType 结果类型 1中间结果 2最终结果
     */
    private void sendHandleMessage(int what, String result, int resultType) {
        haveResult = true;
        Message message = mDialogHandler.obtainMessage();
        message.obj = result;
        message.arg1 = resultType;
        message.what = what;
        message.sendToTarget();
    }

    private void dismissDialog() {
        if (nuiInstance != null) {
            nuiInstance.stopDialog();
        }
    }

    @Override
    public void setNuiResultCallBack(RouterCallBack nuiResultCallBack) {
        this.nuiResultCallBack = nuiResultCallBack;
    }

    @Override
    public void onClickCancel() {
        stopSpeech();
    }

    @Override
    public void onClickRetry() {
        startDialog();
    }

    @Override
    public void init(Context context) {

    }

    @Override
    public void searchClick(String result) {
        ISpeechProvider.super.searchClick(result);
        if (searchClickListener != null) {
            searchClickListener.click(result);
        }
    }

    private SearchClickListener searchClickListener;

    public void setSearchClickListener(SearchClickListener searchClickListener) {
        this.searchClickListener = searchClickListener;
    }

    /**
     * 监听输入变化
     */
    public interface SearchClickListener {
        void click(String result);
    }

}