2

我有一个使用 Kotlin 编写的 RecognitionListener 的项目。语音转文本功能是成功的,但在 Android 9 或 10 设备上测试后出现了一些问题。

在我开始使用 startListening() 函数收听后,它实际上会在一段时间不活动后停止(在 1 秒内)。我添加了一些功能,以便用户可以通过按钮停止并获得结果,或者通过按钮取消并忽略结果。它在 Android 8 设备上进行了很好的测试。但是当我在 Android 10 设备上进行测试时,它从来没有工作过。(也在 Android 9 和 Android 10 的不同设备上测试过......同样的问题)

这是 VoiceRecognition 语音转文本类代码:

package com.primelan.primebot.botVoiceRecognition.voice_recognition

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.speech.RecognitionListener
import android.speech.RecognizerIntent
import android.speech.SpeechRecognizer
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class VoiceRecognition(private val activity: Activity, language: String = "pt_BR") : RecognitionListener {

    private val AudioLogTag = "AudioInput"

    var voiceRecognitionIntentHandler: VoiceRecognitionIntentHandler? = null
    var voiceRecognitionOnResultListener: VoiceRecognitionOnResultListener? = null //Must have this
    var voiceRecognitionLayoutChanger: VoiceRecognitionLayoutChanger? = null

    var isListening = false

    private var enableResult = true
    private val intent: Intent
    private var speech: SpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(activity)

    init {
        speech.setRecognitionListener(this)

        intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
        intent.putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
        )
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language)
    }

    //It is important to put this function inside a clickListener
    fun listen(): Boolean {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.RECORD_AUDIO), 1)
            return false
        }

        speech.startListening(intent)

        Log.i(AudioLogTag, "startListening")

        return true
    }

    //Use this if you want to stop listening but still get recognition results
    fun endListening(){
        Log.i(AudioLogTag, "stopListening")

        speech.stopListening()
        isListening = false
    }

    fun cancelListening(){
        Log.i(AudioLogTag, "cancelListening")

        speech.cancel()
        voiceRecognitionLayoutChanger?.endListeningChangeLayout()
        isListening = false
    }

    override fun onReadyForSpeech(p0: Bundle?) {
        Log.i(AudioLogTag, "onReadyForSpeech")

        voiceRecognitionLayoutChanger?.startListeningChangeLayout()
        isListening = true
    }

    override fun onRmsChanged(p0: Float) {
//        Log.i(LOG_TAG, "onRmsChanged: $p0")
//        progressBar.setProgress((Int) p0)
    }

    override fun onBufferReceived(p0: ByteArray?) {
        Log.i(AudioLogTag, "onBufferReceived: $p0")
    }

    override fun onPartialResults(p0: Bundle?) {
        Log.i(AudioLogTag, "onPartialResults")
    }

    override fun onEvent(p0: Int, p1: Bundle?) {
        Log.i(AudioLogTag, "onEvent")
    }

    override fun onBeginningOfSpeech() {
        Log.i(AudioLogTag, "onBeginningOfSpeech")
    }

    override fun onEndOfSpeech() {
        Log.i(AudioLogTag, "onEndOfSpeech")

        voiceRecognitionLayoutChanger?.endListeningChangeLayout()
        isListening = false

        enableResult = true
    }

    override fun onError(p0: Int) {
        speech.cancel()
        val errorMessage = getErrorText(p0)
        Log.d(AudioLogTag, "FAILED: $errorMessage")
        voiceRecognitionLayoutChanger?.endListeningChangeLayout()
        isListening = false
    }

    override fun onResults(p0: Bundle?) {
        if(enableResult) {
            enableResult = false
            Log.i(AudioLogTag, "onResults")

            val results: ArrayList<String> =
                p0?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION) as ArrayList<String>

            val voiceIntent: Int? = voiceRecognitionIntentHandler?.getIntent(results[0])
            if (voiceIntent != null && voiceIntent != 0) {
                voiceRecognitionIntentHandler?.handle(voiceIntent)
                return
            }

            voiceRecognitionOnResultListener!!.onResult(results[0])
        }
    }

    private fun getErrorText(errorCode: Int): String {
        val message: String
        when (errorCode) {
            SpeechRecognizer.ERROR_AUDIO -> message = "Audio recording error"

            SpeechRecognizer.ERROR_CLIENT -> message = "Client side error"

            SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS -> message = "Insufficient permissions"

            SpeechRecognizer.ERROR_NETWORK -> message = "Network error"

            SpeechRecognizer.ERROR_NETWORK_TIMEOUT -> message = "Network timeout"

            SpeechRecognizer.ERROR_NO_MATCH -> message = "No match"

            SpeechRecognizer.ERROR_RECOGNIZER_BUSY -> message = "RecognitionService busy"

            SpeechRecognizer.ERROR_SERVER -> message = "Error from server"

            SpeechRecognizer.ERROR_SPEECH_TIMEOUT -> message = "No speech input"

            else -> message = "Didn't understand, please try again."
        }
        return message
    }

    //Use it in your overriden onPause function.
    fun onPause() {
        voiceRecognitionLayoutChanger?.endListeningChangeLayout()
        isListening = false

        speech.cancel()
        Log.i(AudioLogTag, "pause")
    }

    //Use it in your overriden onDestroy function.
    fun onDestroy() {
        speech.destroy()
    }
}

如您所见,我提到的函数是endListening()cancelListening()。调用这些函数时,您实际上可以看到 Log,但是如果当前设备使用的是 android 9 或 10,则 cancel() 或 stopListening() 将不会有任何效果。即使 line voiceRecognitionLayoutChanger?.endListeningChangeLayout()fromcancelListening()被执行并带来所需的结果(更改应用程序内的布局)。

android.speech 库有问题吗?或者……有办法解决吗?

4

0 回答 0