安卓,柯特林。由于某些原因,SpeechRecognizer无法正常工作 [英] Android, Kotlin. SpeechRecognizer is not working for some reason
本文介绍了安卓,柯特林。由于某些原因,SpeechRecognizer无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用名为SpeechRecognizer的Android Speech API,试图将语音转换为文本,但由于某种原因,我一点击按钮,就看到消息&cot;Can‘t to to Google Now";,并且窗口关闭,没有等待我的演讲。或者声音断断续续,什么也不会发生。
class MainActivity : AppCompatActivity() {
var voiceButton: Button? = null
var textView: TextView? = null
var listener: Listener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
initializeView()
initializeListeners()
}
fun initializeView() {
voiceButton = findViewById(R.id.voiceButton)
textView = findViewById(R.id.textView)
listener = Listener()
}
fun initializeListeners() {
voiceButton?.setOnClickListener {
val speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
speechRecognizer.setRecognitionListener(listener)
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
speechRecognizer.startListening(intent)
if (intent.resolveActivity(packageManager) != null) {
startActivityForResult(intent, 10)
} else {
Toast.makeText(this, "Unfortunately device not supported", Toast.LENGTH_SHORT).show()
}
}
}
为什么?这个代码有什么问题?我认为这段代码应该可以工作,因为对于其他人来说,它工作得很好。可能此API不支持我的模拟器(Nexus ONE API 22)?我只是不知道有什么问题。
也许你真的知道如何解决这个问题?谢谢,我将非常感谢你的帮助!
如果某人突然遇到类似的问题,这就是我一段时间后解决这个问题的方法:
您需要打开虚拟麦克风使用主机音频输入。转到:更多(右侧)-&麦克风-&>打开虚拟麦克风使用主机音频输入&q;。 此外,您的仿真程序必须安装更高版本的更新,否则语音识别将无法工作。
推荐答案
我认为监听器才是问题所在,您不能只初始化listener = Listener()
并将其传递给Speech Recognizer。它需要接收RecognitionListener
类型的侦听器,该侦听器具有许多可以使用的回调,如onResults
,这表示每次侦听器捕捉到语音时都会有更多回调。
尝试将监听程序更改为listener = object : RecognitionListener{ HERE OVERRIDE THE METHODS }
最终它将看起来是这样的:
listener = object :RecognitionListener {
override fun onReadyForSpeech(params: Bundle?) {
TODO("Not yet implemented")
}
override fun onRmsChanged(rmsdB: Float) {
TODO("Not yet implemented")
}
override fun onBufferReceived(buffer: ByteArray?) {
TODO("Not yet implemented")
}
override fun onPartialResults(partialResults: Bundle?) {
TODO("Not yet implemented")
}
override fun onEvent(eventType: Int, params: Bundle?) {
TODO("Not yet implemented")
}
override fun onBeginningOfSpeech() {
TODO("Not yet implemented")
}
override fun onEndOfSpeech() {
TODO("Not yet implemented")
}
override fun onError(error: Int) {
TODO("Not yet implemented")
}
override fun onResults(results: Bundle?) {
TODO("Not yet implemented")
}
}
您可以阅读有关利用您自己的需求的任何回调 希望能有所帮助
这篇关于安卓,柯特林。由于某些原因,SpeechRecognizer无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文