Access Application() from HiltViewModel @Injection

huangapple go评论39阅读模式
英文:

Access Application() from HiltViewModel @Injection

问题

以下是代码的翻译部分:

@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?) {}
}

请注意,代码中的引号已经被正确地翻译成中文引号。

英文:

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 = &quot;&quot;,
val error: String = &quot;&quot;
)
private val _settings = MutableStateFlow(value = Settings())
val settings: StateFlow&lt;HomeSettings&gt; = _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) ?: &quot;&quot;)
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, &quot;Talk&quot;)
//putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true)
}
init {}
fun startListening(){
speechRecognizer.startListening(recognizerIntent)
}
private fun reactToSpeech(speech: String){
when(speech){
&quot;run&quot; -&gt; Log.w(&quot;App&quot;, &quot;Running!&quot;)
&quot;stop&quot; -&gt; Log.w(&quot;App&quot;, &quot;Stopped!&quot;)
else -&gt; {}
}
}
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?) {}
}

I don't know how I can access the Application() part, or context to be able to access the Speech Service API by Google. If, someone does know how this can be done, please, please let me know. I spent hours Googling today.

答案1

得分: 1

你可以继承AndroidViewModel而不是ViewModel
https://developer.android.com/reference/androidx/lifecycle/AndroidViewModel

AndroidViewModel可以访问Application上下文。

或者,您可以选择将应用程序上下文注入到您的ViewModel中,而无需继承AndroidViewModel,就像这里所示:
https://stackoverflow.com/a/63122193/2877453

英文:

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

AndroidViewModel has access to the Application context.

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

huangapple
  • 本文由 发表于 2023年4月7日 04:22:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定