1

How do you program sound effects in kotlin android Looked all over Yt and there all in Java

Ryan M
  • 18,333
  • 31
  • 67
  • 74

2 Answers2

1

Add/Import your sound effect file to your project and use MediaPlayer like this one

private var BgMusic:MediaPlayer? = null

fun playBgMusic(){
    BgMusic = MediaPlayer.create(this, R.raw.gamebgmusic)
    BgMusic?.setOnPreparedListener{
        BgMusic?.start()
        musicPlaying = true
    }
    BgMusic?.setOnCompletionListener {
        BgMusic?.start()
    }
}

fun pauseBgMusic(){
    BgMusic!!.pause()
}

fun resumeBgMusic(){
    BgMusic!!.start()
}
0

Add your sound effect file into your 'resources' folder in your app project, then call it from whichever activity or fragment you would like to execute it in with SoundPool, a public class that enables you to load the audio resource into memory and play it!

I link you here the SoundPool documentation as well as a blogpost that shows it in action.

Here's also a Kotlin tutorialspoint article.