【问题标题】:Jetpack compose - trying to get sound to play in viewmodel funJetpack compose - 尝试让声音在 viewmodel 中播放
【发布时间】:2021-08-09 08:38:04
【问题描述】:

由于我的应用程序结构,我正在尝试在 @Copmosable 之外播放声音。

我的视图模型中有一个验证例程,根据结果我想触发声音,但我似乎无法在 @Composable 之外获得上下文工作

我在 MasterViewModel 中收到以下错误:

None of the following functions can be called with the arguments supplied.
create(Context!, Uri!) defined in android.media.MediaPlayer
create(Context!, Int) defined in android.media.MediaPlayer

任何指点都会非常感谢!!

package com.example.soundtest

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.example.soundtest.ui.theme.SoundTestTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SoundTestTheme {
                // A surface container using the 'background' color from the theme
                Surface(color = MaterialTheme.colors.background) {
                    Greeting()
                }
            }
        }
    }
}

@Composable
fun Greeting(mastVM: MasterViewModel = MasterViewModel()) {
    Text("Play a sound...")
    mastVM.playSound()
    
}

和 MasterViewModel

package com.example.soundtest

import android.media.MediaPlayer

class MasterViewModel {

    fun playSound() {
        val mp: MediaPlayer = MediaPlayer.create(this, R.raw.correct)
    }
}

我在 res->raw-correct.mp3 下保存了正确的.mp3

MasterViewModel Error

【问题讨论】:

    标签: kotlin android-mediaplayer android-jetpack


    【解决方案1】:

    我搞定了!!!

    我只包括

    @Composable
    fun Greeting(mastVM: MasterViewModel = MasterViewModel()) {
        val context = LocalContext.current
        Text("Play a sound...")
        mastVM.playSound(context: context)
        
    }
    

    然后像这样在 MasterViewModel 中

    fun playSound(context: Context) {
            val mp: MediaPlayer = MediaPlayer.create(context, R.raw.correct)
        }
    

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 2022-11-04
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多