Motivation
When writing app you sometimes want to play some sounds e.g. for notifications.
In Android this can be accomplished by using the SoundPool class.
Resource files
Resource files e.g. your wav shall be placed under
app\src\main\res\raw
Code snippet
This is a working example for playing short sound files. If you want to make a full blown media player you should use the MediaPlayer class
import android.media.AudioManager
import android.media.SoundPool
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var mCSoundOne: Int = 0
private lateinit var mSoundPool: SoundPool
private var mLoaded = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mSoundPool = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
SoundPool.Builder().setMaxStreams(1).build()
} else {
SoundPool(1, AudioManager.STREAM_MUSIC, 1)
}
mSoundPool.setOnLoadCompleteListener(SoundPool.OnLoadCompleteListener { soundPool, sampleId, status ->
mLoaded = true
})
mCSoundOne = mSoundPool.load(applicationContext, R.raw.eins, 1)
}
fun play_one(view: View?) {
if (mLoaded) {
mSoundPool.play(mCSoundOne, 1.0f, 1.0f, 0, 0, 1.0f)
}
}
}