您的位置:首页 > 汽车 > 新车 > HarmonyOS 原生智能之语音识别实战

HarmonyOS 原生智能之语音识别实战

2024/9/20 16:09:47 来源:https://blog.csdn.net/sjw890821sjw/article/details/140881059  浏览:    关键词:HarmonyOS 原生智能之语音识别实战

HarmonyOS 原生智能之语音识别实战

背景

公司很多业务场景使用到了语音识别功能,当时我们的语音团队自研了语音识别模型,方案是云端模型加端侧SDK交互,端侧负责做语音采集、VAD、opus编码,实时传输给云端,云端识别后返回识别结果。这些业务场景在适配鸿蒙的过程发现HarmonyOS 原生智能中提供了本地语音识别SDK,动手封装一波。

场景介绍

原生语音识别能力支持两种模式:

  • 短语音模式(不超过60s)
  • 长语音模式(不超过8h)

API接口介绍

1. 引擎初始化

speechRecognizer.createEngine

let asrEngine: speechRecognizer.SpeechRecognitionEngine;
// 创建引擎,通过callback形式返回
// 设置创建引擎参数
let extraParam: Record<string, Object> = {"locate": "CN", "recognizerMode": "short"};
let initParamsInfo: speechRecognizer.CreateEngineParams = {language: 'zh-CN',online: 1,extraParams: extraParam
};
// 调用createEngine方法
speechRecognizer.createEngine(initParamsInfo, (err: BusinessError, speechRecognitionEngine: speechRecognizer.SpeechRecognitionEngine) => {if (!err) {console.info('Succeeded in creating engine.');// 接收创建引擎的实例asrEngine = speechRecognitionEngine;} else {// 无法创建引擎时返回错误码1002200008,原因:引擎正在销毁中console.error(`Failed to create engine. Code: ${err.code}, message: ${err.message}.`);}
});

主要是需要构建引擎参数speechRecognizer.CreateEngineParams:

  • language:语言
  • online:模式,1为离线,目前只支持离线引擎
  • extraParams:区域信息等
    • locate:区域信息,可选,不设置时默认为“CN”,当前仅支持“CN”
    • recognizerMode:识别模式,包含短语音short与场语音long
      回调中可以查看错误信息:
  1. 无法创建引擎时返回错误码1002200001,原因:语种不支持、模式不支持、初始化超时、资源不存在等导致创建引擎失败
  2. 无法创建引擎时返回错误码1002200006,原因:引擎正在忙碌中,一般多个应用同时调用语音识别引擎时触发
  3. 无法创建引擎时返回错误码1002200008,原因:引擎正在销毁中

2、设置RecognitionListener回调

回调主要处理识别过程中的事件,最主要的就是onResult处理识别内容,不同的对话对应不同的sessionId:

// 创建回调对象
let setListener: speechRecognizer.RecognitionListener = {// 开始识别成功回调onStart(sessionId: string, eventMessage: string) {},// 事件回调onEvent(sessionId: string, eventCode: number, eventMessage: string) {},// 识别结果回调,包括中间结果和最终结果onResult(sessionId: string, result: speechRecognizer.SpeechRecognitionResult) {},// 识别完成回调onComplete(sessionId: string, eventMessage: string) {},// 错误回调,错误码通过本方法返回,如:返回错误码1002200006,识别引擎正忙,引擎正在识别中onError(sessionId: string, errorCode: number, errorMessage: string) {}
}
// 设置回调
asrEngine.setListener(setListener);

3、开始识别

let audioParam: speechRecognizer.AudioInfo = {audioType: 'pcm', sampleRate: 16000, soundChannel: 1, sampleBit: 16};
let extraParam: Record<string, Object> = {"vadBegin": 2000, "vadEnd": 3000, "maxAudioDuration": 40000};
let recognizerParams: speechRecognizer.StartParams = {sessionId: sessionId,audioInfo: audioParam,extraParams: extraParam
};
// 调用开始识别方法
asrEngine.startListening(recognizerParams);

主要是设置开始识别的相关参数:

  • sessionId:会话id,与onResult回调中的sessionId要对应
  • audioInfo:音频配置信息,可选
    • audioType:目前只支持PCM,如果要识别MP3文件等需要解码后再传给引擎
    • sampleRate:音频的采样率,当前仅支持16000采样率
    • sampleBit:音频返回的采样位数,当前仅支持16位
    • soundChannel:音频返回的通道数信息,当前仅支持通道1
    • extraParams:音频的压缩率,pcm格式音频默认为0
  • extraParams:额外配置信息,主要包含:
    • recognitionMode:实时语音识别模式(不传时默认为1)
      • 0:实时录音识别(需应用开启录音权限:ohos.permission.MICROPHONE),若需结束录音,则调用finish方法
      • 1:实时音频转文字识别,开启此模式时需要额外调用writeAudio方法,传入待识别音频流;
    • vadBegin:Voice Activity Detection(VAD)前端点设置,参数范围是[500,10000],不传参时默认为10000ms
    • vadEnd:Voice Activity Detection(VAD)后端点设置。参数范围是[500,10000],不传参时默认为800ms。
    • maxAudioDuration:最大支持音频时长
      • 短语音模式支持范围[20000-60000]ms,不传参时默认20000ms。
      • 长语音模式支持范围[20000 - 8 * 60 * 60 * 1000]ms。
        VAD作用主要是语音活动检测,对静音数据不进行识别

4、传入音频流

asrEngine.writeAudio(sessionId, uint8Array);

向引擎写入音频数据,可以从麦克风或者音频文件中读取音频流。
注意:音频流长度仅支持640或1280。

5、其他接口

  1. listLanguages:查询语音识别服务支持的语种信息
  2. finish:结束识别
  3. 取消识别:cancel
  4. shutdown:释放识别引起资源

最佳实践

实时识别的场景需要从麦克风实时读取音频,写入到asrEngine,在onResult回调中获取识别结果。
配置音频采集参数并创建AudioCapturer实例:

 import { audio } from '@kit.AudioKit';let audioStreamInfo: audio.AudioStreamInfo = {samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, // 采样率channels: audio.AudioChannel.CHANNEL_1, // 通道sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // 采样格式encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // 编码格式};let audioCapturerInfo: audio.AudioCapturerInfo = {source: audio.SourceType.SOURCE_TYPE_MIC,capturerFlags: 0};let audioCapturerOptions: audio.AudioCapturerOptions = {streamInfo: audioStreamInfo,capturerInfo: audioCapturerInfo};audio.createAudioCapturer(audioCapturerOptions, (err, data) => {if (err) {console.error(`Invoke createAudioCapturer failed, code is ${err.code}, message is ${err.message}`);} else {console.info('Invoke createAudioCapturer succeeded.');let audioCapturer = data;}});

这里注意采样率和声道以及采样位数要符合ASR引擎要求:16k采样、单声道、16位采样位数。
接着调用on(‘readData’)方法,订阅监听音频数据读入回调:

 import { BusinessError } from '@kit.BasicServicesKit';import { fileIo } from '@kit.CoreFileKit';let bufferSize: number = 0;class Options {offset?: number;length?: number;}let readDataCallback = (buffer: ArrayBuffer) => {//将buffer写入asr引擎asrEngine.writeAudio(sessionId, new Uint8Array(buffer));}audioCapturer.on('readData', readDataCallback);

这里注意写入buffer的大小显示,ASR只支持640或1280。

总结

本文介绍了 HarmonyOS 官方提供的语音识别能力,详解介绍了ASR引擎接口,最后基于麦克风采集数据实现了实时麦克风语音识别功能。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com