You need to enable JavaScript to run this app. Android SpeechRecognizer自动停止问题及配置失效咨询
优惠活动
大模型
产品
解决方案
定价
更多

Android SpeechRecognizer自动停止问题及配置失效咨询

Android SpeechRecognizer自动停止异常问题

我在使用Android SpeechRecognizer时遇到其自动停止的异常,具体问题如下:

问题1

以下配置参数被完全忽略:

putExtra(
    RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS,
    (5000).toLong()
)
putExtra(
    RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS,
    (5000).toLong()
)
putExtra(
    RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS,
    (5000).toLong()
)

无论如何调整逻辑,上述参数都完全不生效,具体实现见下文代码。

问题2

未进行语音输入时onBeginningOfSpeech()就被触发,随后会在800-1500ms内提前结束识别,回调onEndOfSpeech()并返回ERROR_NO_MATCH错误。
该问题有两个限制条件:

  • 仅在手机联网时出现,若下载离线语言包并开启飞行模式则不会触发
  • 联网状态下微小的背景音都会触发onBeginningOfSpeech(),比如轻触附近物体的声响就会触发该问题,极端安静环境下则不会出现
    两个问题叠加,导致SpeechRecognizer几乎无法正常使用。

问题复现测试说明

上述所有问题均已在运行Android 11系统的无root、功能正常的Pixel 4a设备上验证可复现。

语音识别实现代码

SpeechRecognitionUtil工具类

object SpeechRecognitionUtil {
    const val logTag = "SpeechRecognitionUtil"

    val speechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
        putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
        )
        putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
        putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es-US")
        putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 20)
        putExtra(
            RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS,
            (5000).toLong()
        )
        putExtra(
            RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS,
            (5000).toLong()
        )
        putExtra(
            RecognizerIntent.EXTRA_SPEECH_INPUT_POSSIBLY_COMPLETE_SILENCE_LENGTH_MILLIS,
            (5000).toLong()
        )
    }

    fun setupSpeechRecognizer(
        context: Context,
        onError: (Int) -> Unit = {},
        onReadyForSpeech: (Bundle) -> Unit = {},
        onEndOfSpeech: () -> Unit = {},
        onResults: (Bundle) -> Unit = {},
        onEvent: (Bundle) -> Unit = {},
        onPartialResults: (Bundle) -> Unit = {},
        onBufferReceived_: (ByteArray) -> Unit = {},
        onEvent_: (Int, Bundle) -> Unit = { _, _ -> }
    ): SpeechRecognizer? {
        return when {
            SpeechRecognizer.isRecognitionAvailable(context) -> {
                val speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context)
                speechRecognizer.setRecognitionListener(SimpleRecognitionListener(
                    onError_ = { code: Int ->
                        onError(code)
                    },
                    onBufferReceived_ = {
                        onBufferReceived_(it)
                    },
                    onReadyForSpeech_ = {
                        onReadyForSpeech(it)
                    },
                    onBeginningOfSpeech_ = {
                    },
                    onEvent_ = { integer: Int, bundle: Bundle ->
                        onEvent_(integer, bundle)
                    },
                    onEndOfSpeech_ = {
                        onEndOfSpeech()
                    },
                    onPartialResults_ = {
                        onPartialResults(it)
                    },
                    onResults_ = {
                        onResults(it)
                    }
                ))

                speechRecognizer
            }
            else -> {
                Log.i("SpeechRecognizer", "Recognition is NOT available!")
                null
            }
        }
    }
}

fun Bundle.recognizedWords() = getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
fun Bundle.confidenceScores() = getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES)

class SimpleRecognitionListener(
    val onReadyForSpeech_: (Bundle) -> Unit = {},
    val onBeginningOfSpeech_: () -> Unit = {},
    val onRmsChanged_: (Float) -> Unit = {},
    val onBufferReceived_: (ByteArray) -> Unit = {},
    val onEndOfSpeech_: () -> Unit = {},
    val onError_: (Int) -> Unit = {},
    val onResults_: (Bundle) -> Unit = {},
    val onPartialResults_: (Bundle) -> Unit = {},
    val onEvent_: (Int, Bundle) -> Unit = { _, _ -> }
) : RecognitionListener {
    private var performingSpeechSetup = true

    override fun onReadyForSpeech(bundle: Bundle) {
        Log.d(SpeechRecognitionUtil.logTag, "onReadyForSpeech()::Bundle=$bundle")
        performingSpeechSetup = false
        onReadyForSpeech_(bundle)
    }

    override fun onBeginningOfSpeech() {
        Log.d(SpeechRecognitionUtil.logTag, "onBeginningOfSpeech()")
        onBeginningOfSpeech_()
    }

    override fun onRmsChanged(rms: Float) {
//        Log.i(logTag, "onRmsChanged()::Rms=$rms")
        onRmsChanged_(rms)
    }

    override fun onBufferReceived(byteArray: ByteArray) {
        Log.d(
            SpeechRecognitionUtil.logTag,
            "onBufferReceived()::byteArray=$byteArray, \nwords="
        )
        onBufferReceived_(byteArray)
    }

    override fun onEndOfSpeech() {
        Log.d(SpeechRecognitionUtil.logTag, "onEndOfSpeech()")
        onEndOfSpeech_()
    }

    override fun onError(code: Int) {
        Log.d(SpeechRecognitionUtil.logTag, "onError()::code=$code")
        if (performingSpeechSetup && code == SpeechRecognizer.ERROR_NO_MATCH) return
        else {
            onError_(code)
        }
    }

    override fun onResults(bundle: Bundle) {
        Log.d(
            SpeechRecognitionUtil.logTag,
            "onResults()::Bundle=$bundle, \n" +
                    "Recognized words=${bundle.recognizedWords()}\n" +
                    "Confidence scores=${bundle.confidenceScores()}"
        )
        onResults_(bundle)
    }

    override fun onPartialResults(bundle: Bundle) {
        Log.d(
            SpeechRecognitionUtil.logTag, "onPartialResults()::Bundle=$bundle, \n" +
                    "Recognized words=${bundle.recognizedWords()}"
        )
        onPartialResults_(bundle)
    }

    override fun onEvent(event: Int, bundle: Bundle) {
        Log.d(SpeechRecognitionUtil.logTag, "onEvent()::event=$event, \nbundle=$bundle")
        onEvent_(event, bundle)
    }
}

MainVM实现

class MainVM(app: Application) : AndroidViewModel(app) {
    enum class RecordingState {
        IDLE, RECORDING;
    }


    private var speechRecognizer: SpeechRecognizer? = null
    private val _recording = MutableLiveData(RecordingState.IDLE)
    val recordingState: LiveData<RecordingState> = _recording

    private fun initSpeechRecoginizer() {
        // Destroy old recognizer
        speechRecognizer?.cancel()
        speechRecognizer?.destroy()
        speechRecognizer = null

        // Create new recognizer
        speechRecognizer = SpeechRecognitionUtil.setupSpeechRecognizer(getApplication(),
            onPartialResults = { _ -> },
            onEndOfSpeech = {
                _recording.value = RecordingState.IDLE
            },
            onResults = {},
            onError = {})
    }

    fun startRecording() {
        initSpeechRecoginizer()
        speechRecognizer?.let {
            it.startListening(SpeechRecognitionUtil.speechRecognizerIntent)
            _recording.value = RecordingState.RECORDING
        }
    }

    fun stopRecording() {
        speechRecognizer?.stopListening()
        _recording.value = RecordingState.IDLE
    }

    override fun onCleared() {
        super.onCleared()
        speechRecognizer?.destroy()
        speechRecognizer = null
    }
}

MainActivity实现

class MainActivity : ComponentActivity() {

    private val logTag = "MainActivity"

    @ExperimentalAnimationApi
    @ExperimentalPagerApi
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MaterialTheme {
                ScreenMain()
            }
        }
    }

    @Composable
    private fun ScreenMain() {
        val vm = getViewModel<MainVM>()
        val recordingState by vm.recordingState.observeAsState(RecordingState.IDLE)

        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(20.dp),
            contentAlignment = Alignment.BottomCenter
        ) {
            Button(modifier = Modifier
                .fillMaxWidth(1f)
                .height(50.dp),
                onClick = {
                    when (recordingState) {
                        RecordingState.IDLE -> {
                            vm.startRecording()
                        }
                        RecordingState.RECORDING -> {
                            vm.stopRecording()
                        }
                    }
                }) {
                val textString = when (recordingState) {
                    RecordingState.RECORDING -> {
                        "Stop Recording"
                    }
                    RecordingState.IDLE -> {
                        "Start Recording"
                    }
                }
                Text(textString)
            }
        }
    }
}

Manifest配置

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="some.example.app">

    <queries>
        <intent>
            <action android:name="android.speech.RecognitionService" />
        </intent>
    </queries>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />

    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="EXAMPLE"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Example">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

内容的提问来源于stack exchange,提问作者Tom Taila

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 16:39:01