I am trying to access "Speech to Text" audio in Android, via this code:

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val settingsRepository: SettingsRepository
) : ViewModel(), RecognitionListener
{
    data class SpeechState(
        val spokenText: String = "",
        val error: String = ""
    )

    private val _settings = MutableStateFlow(value = Settings())
    val settings: StateFlow<HomeSettings> = _settings.asStateFlow()
    private val speechState = MutableStateFlow(value = SpeechState())

    private val speechRecognizer: SpeechRecognizer = createSpeechRecognizer(application.applicationContext).apply {
        setRecognitionListener(this@SettingsViewModel)
    }


    private fun updateResults(speechBundle: Bundle?) {
        val userSaid = speechBundle?.getStringArrayList(RESULTS_RECOGNITION)
        speechState.value = speechState.value.copy(spokenText = userSaid?.get(0) ?: "")
        reactToSpeech(speechState.value.spokenText)
    }

    override fun onEndOfSpeech() = speechRecognizer.stopListening()
    override fun onResults(results: Bundle?) = updateResults(speechBundle = results)
    override fun onPartialResults(results: Bundle?) = updateResults(speechBundle = results)


    override fun onError(errorCode: Int) {}

    private val recognizerIntent: Intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
        putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
        putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, application.packageName)
        putExtra(
            RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH
        )
        putExtra(RecognizerIntent.EXTRA_PROMPT, "Talk")
        //putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
    }

    init {}

    fun startListening(){
        speechRecognizer.startListening(recognizerIntent)
    }

    private fun reactToSpeech(speech: String){
        when(speech){
            "run" -> Log.w("App", "Running!")
            "stop" -> Log.w("App", "Stopped!")
            else -> {}
        }
    }

    override fun onReadyForSpeech(p0: Bundle?) {}
    override fun onBeginningOfSpeech() {}
    override fun onRmsChanged(p0: Float) {}
    override fun onBufferReceived(p0: ByteArray?) {}
    override fun onEvent(p0: Int, p1: Bundle?) {}
}

我不知道如何才能访问应用程序()部分或上下文才能访问Google的语音服务API.如果有人知道如何做到这一点,请让我知道.我今天花了好几个小时在谷歌上搜索.

推荐答案

You can extend AndroidViewModel instead of ViewModel
https://developer.android.com/reference/androidx/lifecycle/AndroidViewModel

AndroidViewModel可以访问Application上下文.

Or you can choose to simply inject the application context into your viewmodel without extending AndroidViewModel, like it's shown here:
https://stackoverflow.com/a/63122193/2877453

Android相关问答推荐

写入排除例外以进行依赖性判断

Android添加设置图标齿轮到应用程序信息

如何使用视图模型触发可变状态?

如何将子零部件的大小调整为可以调整大小的父组件大小?

如何go 除回调流中不可用的状态?

MAP函数返回单位列表而不是字符列表

如何从LazyColumn中的图标异步获取可绘制的加载?

如何使用其他组件的位置来定位自定义弹出窗口

如何迭代 SqlDelight Select 结果而不将所有内容加载到内存中?

升级到 Jetpack Compose 物料 list 2023.08.00 需要我将 targetSdk 更改为 34

使用 Dagger Hilt 获取接口的所有实例

获取 ArithmeticException:除以零,但我没有在任何地方除以零

在事件中使用 Context/Toast 时不需要的重组 - Jetpack Compose

组成不重叠的元素

我该怎么做文本计时器

调用时 listFiles() nullpointerexception

重命名列失败的房间自动迁移(NOT NULL 约束失败,生成错误的迁移类)

如何在 Android Studio 中创建新的可组合函数?

如何让用户与任意应用程序共享文件?

多个项目 react-native android 构建错误