我正在使用RecognizerIntent开发一个android应用程序,问题是我不知道如何创建缓冲区来捕获用户输入的语音。我将如何包括缓冲区和识别服务回调。
初始化SpeechRecognizer;
speechRecognizerCallback = SpeechRecognizerListener()
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(context)
mSpeechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 10000)
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.US.toString())
mSpeechRecognizer.setRecognitionListener(speechRecognizerCallback)
回调
inner class SpeechRecognizerListener : RecognitionListener {
override fun onReadyForSpeech(p0: Bundle?) {
}
override fun onRmsChanged(p0: Float) {
}
override fun onBufferReceived(p0: ByteArray?) {
}
override fun onPartialResults(bundle: Bundle) {
val matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
Timber.tag("speech").e(matches.get(0))
}
override fun onEvent(p0: Int, bundle: Bundle) {
val matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
Timber.tag("speech").e(matches.get(0))
}
override fun onBeginningOfSpeech() {
Timber.tag("speech").e("beginning of speech")
}
override fun onEndOfSpeech() {
Timber.tag("speech").e("end of speech")
}
override fun onError(p0: Int) {
}
override fun onResults(bundle: Bundle) {
val matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
Timber.tag("speech").e(matches.get(0))
}
}
在onRequestPermissionsResult第一个请求处开始监听
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
mSpeechRecognizer.startListening(mSpeechRecognizerIntent)
)
}
}
}