SpeechCompService.java
16.4 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
package com.people.comment.manager;
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 androidx.fragment.app.FragmentActivity;
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.base.log.Logger;
import com.people.comment.listener.SpeechResultCallback;
import com.people.speech.Auth;
import com.people.speech.Utils;
import com.wd.common.callback.RouterCallBack;
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.StringUtils;
/**
* @Author LiuKun
* @date:2023/5/5
* @desc:
*/
public class SpeechCompService implements ISpeechProvider {
/**
* 采样率
*/
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 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;
/**
* 数据回调监听
*/
public SpeechResultCallback resultCallback = null;
public void setResultCallback(SpeechResultCallback callback) {
this.resultCallback = callback;
}
/**
* 初始化
*/
@Override
public boolean initSpeechSdk(String accessToken, FragmentActivity context) {
this.mContext = context;
return doInit(accessToken);
}
/**
* 开始录音
*/
@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("没有权限或拒绝权限");
}
});
}
/**
* 停止
*/
@Override
public void stopSpeech() {
haveResult = false;
dismissDialog();
}
/**
* 销毁
*/
@Override
public void release() {
if (nuiInstance != null) {
nuiInstance.release();
}
if (mAudioRecorder != null) {
mAudioRecorder.release();
mAudioRecorder = null;
}
mInit = false;
if (mHandlerThread != null) {
mHandlerThread = null;
}
if (mHandler != null) {
mHandler.removeCallbacksAndMessages(null);
mHandler = null;
}
if (mDialogHandler != null) {
mDialogHandler.removeCallbacksAndMessages(null);
}
if (mContext != null) {
mContext = null;
}
if (resultCallback != null) {
resultCallback = null;
}
haveResult = false;
}
@Override
public void setNuiResultCallBack(RouterCallBack nuiResultCallBack) {
}
@Override
public void init(Context context) {
}
/**
* 开始录音
*/
private void startDialog() {
showVoiceSearchDialog();
sendHandleEmptyMessage(SPEAK_START);
mHandler.post(() -> {
if (nuiInstance != null) {
int ret = nuiInstance.startDialog(Constants.VadMode.TYPE_P2T, genDialogParams());
}
});
}
/**
* 开始录音
*/
private void showVoiceSearchDialog() {
if (mContext == null || mContext.isDestroyed() || mContext.isFinishing()) {
return;
}
if (null != resultCallback) {
resultCallback.start();
}
}
/**
* 获取录音实例
*/
@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 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);
}
/**
* 初始化handler
*/
private void initHandler() {
mHandlerThread = new HandlerThread("process_thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
}
/**
* 发送广播信息
*/
private void sendHandleEmptyMessage(int what) {
Message message = mDialogHandler.obtainMessage();
message.what = what;
message.sendToTarget();
}
/**
* @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();
}
/**
* 初始化sdk
*/
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;
}
/**
* 内部调用
*/
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;
}
/**
* Auth实现访问阿里云鉴权SDK动态获取token, 通过网络请求,获取Token信息
* token 24小时过期,因此需要通过阿里云SDK来进行更新
*/
private String genInitParams(String workpath, String debugpath, String accessToken) {
String str = "";
try {
JSONObject object = Auth.getNetAliYunTicket(accessToken);
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 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:
String content = (String) msg.obj;
int arg1 = msg.arg1;
if (arg1 == 2) {
mHandler.postDelayed(() -> {
if (resultCallback != null) {
resultCallback.result(content);
}
stopSpeech();
haveResult = false;
}, 200);
}
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() {
@Override
public void onNuiEventCallback(Constants.NuiEvent event, final int resultCode, final int arg2, KwsResult kwsResult, AsrResult asrResult) {
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(() -> 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) {
Logger.t("ouyang").e("SPEAK_ERROR 录音错误>>>>暂停了");
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();
}
}
/**
* 停止
*/
private void dismissDialog() {
if (nuiInstance != null) {
nuiInstance.stopDialog();
}
}
}