android Demo
vosk github 地址
Vosk Android Demo 是一个用于 Android 平台的离线语音识别演示项目,基于 Kaldi 和 Vosk 库实现。该项目允许开发者在移动应用中集成离线语音识别和说话人识别功能。
1.官网下载相应的语言模型

image.png
2.在自己的项目添加 相关依赖
api 'net.java.dev.jna:jna:5.13.0@aar'
api 'com.alphacephei:vosk-android:0.3.70'
api project('models')
这个 api project('models') 就是我们依赖的语言模型 中英文 其他语言也有
3.初始化语言模型
private void initModel() {
StorageService.unpack(activity, "vosk-model-small-cn", "model",
(model) -> {
this.model = model;
setUiState(STATE_READY);
},
(exception) -> setErrorState("Failed to unpack the model" + exception.getMessage()));
}
4.初始化语音识别和回调接口
public void recognizeMicrophone() {
if (speechService != null) {
speechService.setPause(false);
} else {
try {
// 添加识别命令
List<String> list = getCommandList();
String grammar= GsonUtil.getGson().toJson(list);
Log.d(TAG, "recognizeMicrophone: "+ grammar);
Recognizer rec = new Recognizer(model, 16000.0f,grammar);
// Recognizer rec = new Recognizer(model, 16000.0f);
speechService = new SpeechService(rec, 16000.0f);
speechService.startListening(this);
} catch (IOException e) {
Log.d(TAG, "recognizeMicrophone: IOException"+e.getMessage());
setErrorState(e.getMessage());
}
}
}
5.识别回调RecognitionListener处理,有个 过程回调, 结果回调, 在这里进行判断识别的内容,做业务处理
@Override
public void onResult(String hypothesis) {
if (recognitionCallback != null) {
recognitionCallback.onResult(hypothesis);
}
}
@Override
public void onFinalResult(String hypothesis) {
setUiState(STATE_DONE);
if (speechStreamService != null) {
speechStreamService = null;
}
// 添加最终结果回调
if (recognitionCallback != null) {
recognitionCallback.onFinalResult(hypothesis);
}
}
@Override
public void onPartialResult(String hypothesis) {
// 添加部分结果回调
if (recognitionCallback != null) {
recognitionCallback.onPartialResult(hypothesis);
}
}
6.暂停语音识别和关闭
//暂停
speechService.setPause(true);
//关闭
if (speechService != null) {
speechService.stop();
speechService.shutdown();
}
7.小问题
如果需要 自己定义高频词汇,可以通过 grammar添加JSON字符串,进行添加, 但是就只能识别你添加的词汇,其他的词汇又无法识别了
适合用于 命令识别功能,通过识别命令,进行操作,类似物联设备的语音识别命令
Recognizer rec = new Recognizer(model, 16000.0f,grammar);