Skip to content

Commit

Permalink
Cleaning recognizer properly on android (#32)
Browse files Browse the repository at this point in the history
* Cleaning recognizer properly on android

* cleaning model if not clean yet before load model
  • Loading branch information
kingdcreations committed Mar 14, 2023
1 parent 502a744 commit 493c527
Showing 1 changed file with 24 additions and 22 deletions.
46 changes: 24 additions & 22 deletions android/src/main/java/com/reactnativevosk/VoskModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class VoskModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
private var model: Model? = null
private var speechService: SpeechService? = null
private var context: ReactApplicationContext? = reactContext
private var recognizer: Recognizer? = null

override fun getName(): String {
return "Vosk"
Expand All @@ -23,10 +24,8 @@ class VoskModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
val text = getHypothesisText(hypothesis)

// Stop recording if data found
if (text != null && text.isNotEmpty() && speechService != null) {
speechService!!.stop()
speechService = null
// Display data
if (text != null && text.isNotEmpty()) {
cleanRecognizer();
sendEvent("onResult", text)
}
}
Expand Down Expand Up @@ -93,10 +92,7 @@ class VoskModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo

@ReactMethod
fun loadModel(path: String, promise: Promise) {
if (this.model != null) {
this.model!!.close(); // unload model
this.model = null;
}
cleanModel();
StorageService.unpack(context, path, "models",
{ model: Model? ->
this.model = model
Expand All @@ -118,13 +114,13 @@ class VoskModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
sendEvent("onError", "Recognizer is already in use")
} else {
try {
val rec =
recognizer =
if (grammar != null)
Recognizer(model, 16000.0f, makeGrammar(grammar))
else
Recognizer(model, 16000.0f)

speechService = SpeechService(rec, 16000.0f)
speechService = SpeechService(recognizer, 16000.0f)
speechService!!.startListening(this)
sendEvent("onStart")

Expand All @@ -133,27 +129,33 @@ class VoskModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaMo
}
}
}

@ReactMethod
fun stop() {

private fun cleanRecognizer() {
if (speechService != null) {
speechService!!.stop()
speechService!!.shutdown();
speechService = null
}
if (recognizer != null) {
recognizer!!.close();
recognizer = null;
}
}

@ReactMethod
fun unload() {

private fun cleanModel() {
if (this.model != null) {
this.model!!.close(); // unload model
this.model!!.close();
this.model = null;
}
}

if (speechService != null) {
speechService!!.stop();
speechService!!.shutdown();
}
@ReactMethod
fun stop() {
cleanRecognizer();
}

@ReactMethod
fun unload() {
cleanRecognizer();
cleanModel();
}
}

0 comments on commit 493c527

Please sign in to comment.