@UniJSMethod(uiThread = false)
fun openAudio(jsCallback: UniJSCallback?) {
mUniSDKInstance.runOnUiThread {
if (jsCallback != null) {
processSamples(jsCallback)
}
}
}
private fun processSamples(jsCallback: UniJSCallback) {
Log.i(TAG, "processing samples")
val result = JSONObject()
val resultData = JSONObject()
val interval = 0.1 // i.e., 100 ms
val bufferSize = (interval * sampleRateInHz).toInt() // in samples
val buffer = ShortArray(bufferSize)
while (isRecording) {
val ret = audioRecord?.read(buffer, 0, buffer.size)
if (ret != null && ret > 0) {
val samples = FloatArray(ret) { buffer[it] / 32768.0f }
model.acceptSamples(samples)
while (model.isReady()) {
model.decode()
}
// mUniSDKInstance.runOnUiThread {
UniLogUtils.i(TAG, "Handler is running: ${handler.looper.isCurrentThread}")
// handler.post {
val isEndpoint = model.isEndpoint()
val text = model.text
if (text.isNotBlank()) {
if (lastText.isBlank()) {
resultData.put("text", "${idx}: ${text}");
resultData.put("isEndpoint", isEndpoint);
result.put("code", 0)
result.put("data", resultData)
result.put("msg", "获取语音文字成功")
} else {
resultData.put("text", "${lastText}\n${idx}: ${text}");
resultData.put("isEndpoint", isEndpoint);
result.put("code", 0)
result.put("data", resultData)
result.put("msg", "获取语音文字成功")
}
}
if (isEndpoint) {
model.reset()
// if (text.isNotBlank()) {
// lastText = "${lastText}\n${idx}: ${text}"
// idx += 1
// }
}
jsCallback.invoke(result)
// }
// }
}
}
}
现在的问题就是代码 里的子线程一直在循环执行获取值,但是jsCallback.invoke(result)一直没执行,把值返回到前端去。。。
就想知道这个的解决办法,或者提供一个uniapp 原生插件的子线程套子线程的写法-.-
handler.post {} 把jsCallback.invoke(result)提到主线程去执行也不行,,,,,用了之后handler.post {} 这里面的代码不执行-.-,或者说偶尔执行,吐了
2 个回复
9***@qq.com (作者)
被折磨了一波,总算解决了
js代码
调用代码
android Kotlin 代码
@UniJSMethod(uiThread = true)
fun openAudio(jsCallback: UniJSCallback?) {
val result = JSONObject()
if (!isRecording) {
val ret = initMicrophone()
if (!ret) {
UniLogUtils.e(TAG, "Failed to initialize microphone")
if (jsCallback != null) {
result.put("code", -1)
result.put("data", null)
result.put("msg", "Failed to initialize microphone")
jsCallback.invoke(result)
}
return
}
UniLogUtils.i(TAG, "state: ${audioRecord?.state}")
audioRecord!!.startRecording()
isRecording = true
model.reset()
lastText = ""
idx = 0
// mUniSDKInstance.runOnUiThread {
// processSamples()
// }
UniLogUtils.i(TAG, "Started recording")
if (jsCallback != null) {
result.put("code", 0)
result.put("data", null)
result.put("msg", "开启语音监听成功")
jsCallback.invoke(result)
}
} else {
isRecording = false
audioRecord!!.stop()
audioRecord!!.release()
audioRecord = null
UniLogUtils.i(TAG, "Stopped recording")
实现循环传参
private fun processSamples() {
UniLogUtils.i(TAG, "processing samples")
val resultData = JSONObject()
这样就能把android识别到的语音转成文字实时发送到uniapp去使用了
希望下一个兄弟不会被折磨把,恶心人,
我特么头皮抠烂
s***@gmail.com
被折磨中...