i am trying to create a simple app. But there’s a problem occurring which i couldn’t resolve by my own researches.
My whish is, to play different sounds when press different buttons.
At first,
myMP.create(context, uri)
//then
myMP.start()
is playing the sound! Although, i couldn’t managed to play the second sound in the same folder.
Here is the full code in advance.
package com.example.buttonsound
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.tooling.preview.Preview
import com.example.buttonsound.ui.theme.ButtonSoundTheme
import androidx.compose.ui.unit.dp
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ButtonSoundTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
myPlaySound()
}
}
}
}
}
@Composable
fun myPlaySound(){
//context
val view = LocalView.current
var myMP = MediaPlayer.create(view.context, R.raw.sound1)
Column {
Button(onClick = { myMP.start() }) {
Text(text = "Sound1")
}
val s2Uri = Uri.parse("android.resource://com.example.buttonsound/"+ R.raw.sound2)
Button(onClick = { myMP.setDataSource(view.context, s2Uri)
myMP.start() }) {
Text(text = "Sound2")
}
}
}
I read the documentation, checked several examples about it and encountered several issues.
One of them is about the file path, it has to be Uri, so i used the Uri.parse(path) but still i couldn’t made it…
Maybe there’s another way to change the resource other than myMP.setDataSource(…)
Any guidance will be appreciated.
Rather than having the solution, i want to explain the process, what i think of, when using the mediaplayer.
So there’s a mediaplayer library, import and get an instance
then play a sound.
For another button, i have to use previous instance but with different sound file.
setdatasource with the file intended to play the sound.
Last, play it with instance.start()
Note: There’s another issue almost same with mine. Although i read that issue, i couldn’t understand it either.