服务器之家

服务器之家 > 正文

鸿蒙AI能力之语音识别

时间:2021-12-24 19:32     来源/作者:鸿蒙社区

鸿蒙AI能力之语音识别

文章旨在帮助大家开发录音及语音识别时少踩一点坑。

效果

鸿蒙AI能力之语音识别

左侧为简易UI布局及识别成果,右侧为网易云播放的测试音频。

开发步骤

IDE安装、项目创建等在此略过。App采用SDK版本为API 6,使用JS UI。

1.权限申请

AI语音识别不需要任何权限,但此处使用到麦克风录制音频,就需要申请麦克风权限。

在config.json配置文件中添加权限:

  1. "reqPermissions": [
  2. {
  3. "name": "ohos.permission.MICROPHONE"
  4. }
  5. ]

在MainAbility中显示申明麦克风权限:

  1. @Override
  2. public void onStart(Intent intent) {
  3. super.onStart(intent);
  4. requestPermission();
  5. }
  6. //获取权限
  7. private void requestPermission() {
  8. String[] permission = {
  9. "ohos.permission.MICROPHONE",
  10. };
  11. List applyPermissions = new ArrayList<>();
  12. for (String element : permission) {
  13. if (verifySelfPermission(element) != 0) {
  14. if (canRequestPermission(element)) {
  15. applyPermissions.add(element);
  16. }
  17. }
  18. }
  19. requestPermissionsFromUser(applyPermissions.toArray(new String[0]), 0);
  20. }

2.创建音频录制的工具类

首先创建音频录制的工具类AudioCaptureUtils。

而音频录制需要用到AudioCapturer类,而在创建AudioCapture类时又会用到AudioStreamInfo类及AudioCapturerInfo类,所以我们分别申明以上3个类的变量。

  1. private AudioStreamInfo audioStreamInfo;
  2. private AudioCapturer audioCapturer;
  3. private AudioCapturerInfo audioCapturerInfo;

在语音识别时对音频的录制是由限制的,限制如下:

鸿蒙AI能力之语音识别

所以我们在录制音频时需要注意:

1.采样率16000HZ

2.声道为单声道

3.仅支持普通话

作为工具类,为了使AudioCaptureUtils能多处使用,我们在创建构造函数时,提供声道与频率的参数重载,并在构造函数中初始化AudioStreamInfo类及AudioCapturerInfo类。

  1. //channelMask 声道
  2. //SampleRate 频率
  3. public AudioCaptureUtils(AudioStreamInfo.ChannelMask channelMask, int SampleRate) {
  4. this.audioStreamInfo = new AudioStreamInfo.Builder()
  5. .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT)
  6. .channelMask(channelMask)
  7. .sampleRate(SampleRate)
  8. .build();
  9. this.audioCapturerInfo = new AudioCapturerInfo.Builder().audioStreamInfo(audioStreamInfo).build();
  10. }

在init函数中进行audioCapturer的初始化,在初始化时对音效进行设置,默认为降噪模式。

  1. //packageName 包名
  2. public void init(String packageName) {
  3. this.init(SoundEffect.SOUND_EFFECT_TYPE_NS,packageName );
  4. }
  5. //soundEffect 音效uuid
  6. //packageName 包名
  7. public void init(UUID soundEffect, String packageName) {
  8. if (audioCapturer == null || audioCapturer.getState() == AudioCapturer.State.STATE_UNINITIALIZED)
  9. audioCapturer = new AudioCapturer(this.audioCapturerInfo);
  10. audioCapturer.addSoundEffect(soundEffect, packageName);
  11. }

初始化后提供start、stop和destory方法,分别开启音频录制、停止音频录制和销毁,此处都是调用AudioCapturer类中对应函数。

  1. public void stop(){
  2. this.audioCapturer.stop();
  3. }
  4. public void destory(){
  5. this.audioCapturer.stop();
  6. this.audioCapturer.release();
  7. }
  8. public Boolean start() {
  9. if (audioCapturer == null)
  10. return false;
  11. return audioCapturer.start();
  12. }

提供一个读取音频流的方法及获取AudioCapturer实例的方法。

  1. //buffers 需要写入的数据流
  2. //offset 数据流的偏移量
  3. //byteslength 数据流的长度
  4. public int read(byte[] buffers, int offset, int bytesLength){
  5. return audioCapturer.read(buffers,offset,bytesLength);
  6. }
  7. //获取AudioCapturer的实例audioCapturer
  8. public AudioCapturer get(){
  9. return this.audioCapturer;
  10. }

3.创建语音识别的工具类

在上面我们已经创建好一个音频录制的工具类,接下来在创建一个语音识别的工具类 AsrUtils。

我们再回顾一下语音识别的约束与限制:

鸿蒙AI能力之语音识别

在此补充一个隐藏限制,PCM流的长度只允许640与1280两种长度,也就是我们音频读取流时只能使用640与1280两种长度。

接下来我们定义一些基本常量:

  1. //采样率限定16000HZ
  2. private static final int VIDEO_SAMPLE_RATE = 16000;
  3. //VAD结束时间 默认2000ms
  4. private static final int VAD_END_WAIT_MS = 2000;
  5. //VAD起始时间 默认4800ms
  6. //这两参数与识别准确率有关,相关信息可百度查看,在此使用系统默认
  7. private static final int VAD_FRONT_WAIT_MS = 4800;
  8. //输入时常 20000ms
  9. private static final int TIMEOUT_DURATION = 20000;
  10. //PCM流长度仅限640或1280
  11. private static final int BYTES_LENGTH = 1280;
  12. //线程池相关参数
  13. private static final int CAPACITY = 6;
  14. private static final int ALIVE_TIME = 3;
  15. private static final int POOL_SIZE = 3;

因为要在后台持续录制音频,所以需要开辟一个新的线程。此处用到java的ThreadPoolExecutor类进行线程操作。

定义一个线程池实例以及其它相关属性如下:

  1. //录音线程
  2. private ThreadPoolExecutor poolExecutor;
  3. /* 自定义状态信息
  4. ** 错误:-1
  5. ** 初始:0
  6. ** init:1
  7. ** 开始输入:2
  8. ** 结束输入:3
  9. ** 识别结束:5
  10. ** 中途出识别结果:9
  11. ** 最终识别结果:10
  12. */
  13. public int state = 0;
  14. //识别结果
  15. public String result;
  16. //是否开启语音识别
  17. //当开启时才写入PCM流
  18. boolean isStarted = false;
  19. //ASR客户端
  20. private AsrClient asrClient;
  21. //ASR监听对象
  22. private AsrListener listener;
  23. AsrIntent asrIntent;
  24. //音频录制工具类
  25. private AudioCaptureUtils audioCaptureUtils;

在构造函数中初始化相关属性:

  1. public AsrUtils(Context context) {
  2. //实例化一个单声道,采集频率16000HZ的音频录制工具类实例
  3. this.audioCaptureUtils = new AudioCaptureUtils(AudioStreamInfo.ChannelMask.CHANNEL_IN_MONO, VIDEO_SAMPLE_RATE);
  4. //初始化降噪音效
  5. this.audioCaptureUtils.init("com.panda_coder.liedetector");
  6. //结果值设为空
  7. this.result = "";
  8. //给录音控件初始化一个新的线程池
  9. poolExecutor = new ThreadPoolExecutor(
  10. POOL_SIZE,
  11. POOL_SIZE,
  12. ALIVE_TIME,
  13. TimeUnit.SECONDS,
  14. new LinkedBlockingQueue<>(CAPACITY),
  15. new ThreadPoolExecutor.DiscardOldestPolicy());
  16. if (asrIntent == null) {
  17. asrIntent = new AsrIntent();
  18. //设置音频来源为PCM流
  19. //此处也可设置为文件
  20. asrIntent.setAudioSourceType(AsrIntent.AsrAudioSrcType.ASR_SRC_TYPE_PCM);
  21. asrIntent.setVadEndWaitMs(VAD_END_WAIT_MS);
  22. asrIntent.setVadFrontWaitMs(VAD_FRONT_WAIT_MS);
  23. asrIntent.setTimeoutThresholdMs(TIMEOUT_DURATION);
  24. }
  25. if (asrClient == null) {
  26. //实例化AsrClient
  27. asrClient = AsrClient.createAsrClient(context).orElse(null);
  28. }
  29. if (listener == null) {
  30. //实例化MyAsrListener
  31. listener = new MyAsrListener();
  32. //初始化AsrClient
  33. this.asrClient.init(asrIntent, listener);
  34. }
  35. }
  36. //够建一个实现AsrListener接口的类MyAsrListener
  37. class MyAsrListener implements AsrListener {
  38. @Override
  39. public void onInit(PacMap pacMap) {
  40. HiLog.info(TAG, "====== init");
  41. state = 1;
  42. }
  43. @Override
  44. public void onBeginningOfSpeech() {
  45. state = 2;
  46. }
  47. @Override
  48. public void onRmsChanged(float v) {
  49. }
  50. @Override
  51. public void onBufferReceived(byte[] bytes) {
  52. }
  53. @Override
  54. public void onEndOfSpeech() {
  55. state = 3;
  56. }
  57. @Override
  58. public void onError(int i) {
  59. state = -1;
  60. if (i == AsrError.ERROR_SPEECH_TIMEOUT) {
  61. //当超时时重新监听
  62. asrClient.startListening(asrIntent);
  63. } else {
  64. HiLog.info(TAG, "======error code:" + i);
  65. asrClient.stopListening();
  66. }
  67. }
  68. //注意与onIntermediateResults获取结果值的区别
  69. //pacMap.getString(AsrResultKey.RESULTS_RECOGNITION);
  70. @Override
  71. public void onResults(PacMap pacMap) {
  72. state = 10;
  73. //获取最终结果
  74. //{"result":[{"confidence":0,"ori_word":"你 好 ","pinyin":"NI3 HAO3 ","word":"你好。"}]}
  75. String results = pacMap.getString(AsrResultKey.RESULTS_RECOGNITION);
  76. ZSONObject zsonObject = ZSONObject.stringToZSON(results);
  77. ZSONObject infoObject;
  78. if (zsonObject.getZSONArray("result").getZSONObject(0) instanceof ZSONObject) {
  79. infoObject = zsonObject.getZSONArray("result").getZSONObject(0);
  80. String resultWord = infoObject.getString("ori_word").replace(" ", "");
  81. result += resultWord;
  82. }
  83. }
  84. //中途识别结果
  85. //pacMap.getString(AsrResultKey.RESULTS_INTERMEDIATE)
  86. @Override
  87. public void onIntermediateResults(PacMap pacMap) {
  88. state = 9;
  89. // String result = pacMap.getString(AsrResultKey.RESULTS_INTERMEDIATE);
  90. // if (result == null)
  91. // return;
  92. // ZSONObject zsonObject = ZSONObject.stringToZSON(result);
  93. // ZSONObject infoObject;
  94. // if (zsonObject.getZSONArray("result").getZSONObject(0) instanceof ZSONObject) {
  95. // infoObject = zsonObject.getZSONArray("result").getZSONObject(0);
  96. // String resultWord = infoObject.getString("ori_word").replace(" ", "");
  97. // HiLog.info(TAG, "=========== 9 " + resultWord);
  98. // }
  99. }
  100. @Override
  101. public void onEnd() {
  102. state = 5;
  103. //当还在录音时,重新监听
  104. if (isStarted)
  105. asrClient.startListening(asrIntent);
  106. }
  107. @Override
  108. public void onEvent(int i, PacMap pacMap) {
  109. }
  110. @Override
  111. public void onAudioStart() {
  112. state = 2;
  113. }
  114. @Override
  115. public void onAudioEnd() {
  116. state = 3;
  117. }
  118. }

开启识别与停止识别的函数:

  1. public void start() {
  2. if (!this.isStarted) {
  3. this.isStarted = true;
  4. asrClient.startListening(asrIntent);
  5. poolExecutor.submit(new AudioCaptureRunnable());
  6. }
  7. }
  8. public void stop() {
  9. this.isStarted = false;
  10. asrClient.stopListening();
  11. audioCaptureUtils.stop();
  12. }
  13. //音频录制的线程
  14. private class AudioCaptureRunnable implements Runnable {
  15. @Override
  16. public void run() {
  17. byte[] buffers = new byte[BYTES_LENGTH];
  18. //开启录音
  19. audioCaptureUtils.start();
  20. while (isStarted) {
  21. //读取录音的PCM流
  22. int ret = audioCaptureUtils.read(buffers, 0, BYTES_LENGTH);
  23. if (ret <= 0) {
  24. HiLog.error(TAG, "======Error read data");
  25. } else {
  26. //将录音的PCM流写入到语音识别服务中
  27. //若buffer的长度不为1280或640时,则需要手动处理成1280或640
  28. asrClient.writePcm(buffers, BYTES_LENGTH);
  29. }
  30. }
  31. }
  32. }

识别结果是通过listener的回调获取的结果,所以我们在处理时是将结果赋值给result,通过getresult或getResultAndClear函数获取结果。

  1. public String getResult() {
  2. return result;
  3. }
  4. public String getResultAndClear() {
  5. if (this.result == "")
  6. return "";
  7. String results = getResult();
  8. this.result = "";
  9. return results;
  10. }

4.创建一个简易的JS UI,并通过JS调ServerAbility的能力调用Java

hml代码:

  1. "container">
  2. "title">
  3. 语音识别内容: {{ text }}

样式代码:

  1. .container {
  2. flex-direction: column;
  3. justify-content: flex-start;
  4. align-items: center;
  5. width: 100%;
  6. height: 100%;
  7. padding: 10%;
  8. }
  9. .title {
  10. font-size: 20px;
  11. color: #000000;
  12. opacity: 0.9;
  13. text-align: left;
  14. width: 100%;
  15. margin: 3% 0;
  16. }
  17. .btn{
  18. padding: 10px 20px;
  19. margin:3px;
  20. border-radius: 6px;
  21. }

js逻辑控制代码:

  1. //js调Java ServiceAbility的工具类
  2. import { jsCallJavaAbility } from '../../common/JsCallJavaAbilityUtils.js';
  3. export default {
  4. data: {
  5. text: ""
  6. },
  7. //开启事件
  8. start() {
  9. jsCallJavaAbility.callAbility("ControllerAbility",100,{}).then(result=>{
  10. console.log(result)
  11. })
  12. },
  13. //关闭事件
  14. stop() {
  15. jsCallJavaAbility.callAbility("ControllerAbility",101,{}).then(result=>{
  16. console.log(result)
  17. })
  18. jsCallJavaAbility.unSubAbility("ControllerAbility",201).then(result=>{
  19. if (result.code == 200) {
  20. console.log("取消订阅成功");
  21. }
  22. })
  23. },
  24. //订阅Java端结果事件
  25. sub() {
  26. jsCallJavaAbility.subAbility("ControllerAbility", 200, (data) => {
  27. let text = data.data.text
  28. text && (this.text += text)
  29. }).then(result => {
  30. if (result.code == 200) {
  31. console.log("订阅成功");
  32. }
  33. })
  34. }
  35. }

ServerAbility:

  1. public class ControllerAbility extends Ability {
  2. AnswerRemote remote = new AnswerRemote();
  3. AsrUtils asrUtils;
  4. //订阅事件的委托
  5. private static HashMap<Integer, IRemoteObject> remoteObjectHandlers = new HashMap<Integer, IRemoteObject>();
  6. @Override
  7. public void onStart(Intent intent) {
  8. HiLog.error(LABEL_LOG, "ControllerAbility::onStart");
  9. super.onStart(intent);
  10. //初始化语音识别工具类
  11. asrUtils = new AsrUtils(this);
  12. }
  13. @Override
  14. public void onCommand(Intent intent, boolean restart, int startId) {
  15. }
  16. @Override
  17. public IRemoteObject onConnect(Intent intent) {
  18. super.onConnect(intent);
  19. return remote.asObject();
  20. }
  21. class AnswerRemote extends RemoteObject implements IRemoteBroker {
  22. AnswerRemote() {
  23. super("");
  24. }
  25. @Override
  26. public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
  27. Map zsonResult = new HashMap();
  28. String zsonStr = data.readString();
  29. ZSONObject zson = ZSONObject.stringToZSON(zsonStr);
  30. switch (code) {
  31. case 100: {
  32. //当js发送code为100时,开启语音识别
  33. asrUtils.start();
  34. break;
  35. }
  36. case 101: {
  37. //当js发送code为101时,关闭语音识别
  38. asrUtils.stop();
  39. break;
  40. }
  41. case 200: {
  42. //当js发送code为200时,订阅获取识别结果事件
  43. remoteObjectHandlers.put(200 ,data.readRemoteObject());
  44. //定时获取语音识别结果并返回JS UI
  45. getAsrText();
  46. break;
  47. }
  48. default: {
  49. reply.writeString("service not defined");
  50. return false;
  51. }
  52. }
  53. reply.writeString(ZSONObject.toZSONString(zsonResult));
  54. return true;
  55. }
  56. @Override
  57. public IRemoteObject asObject() {
  58. return this;
  59. }
  60. }
  61. public void getAsrText() {
  62. new Thread(() -> {
  63. while (true) {
  64. try {
  65. Thread.sleep(1 * 500);
  66. Map zsonResult = new HashMap();
  67. zsonResult.put("text",asrUtils.getResultAndClear());
  68. ReportEvent(200, zsonResult);
  69. } catch (RemoteException | InterruptedException e) {
  70. break;
  71. }
  72. }
  73. }).start();
  74. }
  75. private void ReportEvent(int remoteHandler, Object backData) throws RemoteException {
  76. MessageParcel data = MessageParcel.obtain();
  77. MessageParcel reply = MessageParcel.obtain();
  78. MessageOption option = new MessageOption();
  79. data.writeString(ZSONObject.toZSONString(backData));
  80. IRemoteObject remoteObject = remoteObjectHandlers.get(remoteHandler);
  81. remoteObject.sendRequest(100, data, reply, option);
  82. reply.reclaim();
  83. data.reclaim();
  84. }
  85. }

至此简易的语音识别功能完毕。

相关演示:https://www.bilibili.com/video/BV1E44y177hv/

完整代码开源:https://gitee.com/panda-coder/harmonyos-apps/tree/master/AsrDemo

原文链接:https://harmonyos.51cto.com

标签:

相关文章

热门资讯

yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整
蜘蛛侠3英雄无归3正片免费播放 蜘蛛侠3在线观看免费高清完整 2021-08-24
2021年耽改剧名单 2021要播出的59部耽改剧列表
2021年耽改剧名单 2021要播出的59部耽改剧列表 2021-03-05
返回顶部