I have searched and read several SoundPool questions and how to construct it in Android Studio in Kotlin language for atleast an hour but I do not understand and I can't get it to work. The videos usually just writes code and does not explain what each part do what so it is hard to rewrite the code for my app.
Can someone please explain it step by step for me or atleast point me to a website or video that can? I need to understand all the steps since I am new to this.
This is what I want to do: I want to play a short wav file when the user reach the win activity. I also want to play a short wav file when the user answers correct on the questions leading to the win activity.
So the "correct answer" sound will play in my playerCard function and the "You won" sound will play when the win activity starts. I have created a raw resource file in my res and copied the wav files there. If you want to see the code this is my github : https://github.com/Noccis/TonisApp.git
I am thankful for any help. /Toni
I haven't used SoundPool
but I can try and give you some help. First of all, have a look at the docs if you haven't already - near the bottom of the intro they describe something like what you're doing. Looks like what you basically need to do is:
SoundPool.Builder().build()
(the defaults look fine for testing)SoundPool
and call one of the load
methods for each file you want to addplay
on it, passing the ID for a sound (which the load
call gives you)That should work pretty easily - I'd set it up in a single activity so you can test it, maybe add a button that makes a noise when you click it. Your biggest problem is probably gonna be loading the sounds - personally, I'd stick them in assets
and use the load call that takes an AssetFileDescriptor
val assetManager = context.getAssets()
val winSoundFile = assetManager.openFd("sounds/winners.wav")
val winSoundID = soundPool.load(winSoundFile, 1)
but that's more for an ease of organisation thing - you can keep them in res/raw
if you like, and just do
val winSoundId = soundPool.load(context, R.raw.winners, 1)
The other stuff in the docs is what you need to care about, e.g. you should be calling release()
on the sound pool when you're not using it. That means if you don't expect to be playing sounds in the near future, like if the game ends, or if your app goes into the background (so call release
in onPause
or onStop
). Recreate the sound pool when you need it again.
And remember if you switch activities, and the pool was held in the other one, that's gone (and should have been release
d!) and you need to create a new one. Just focus on a simple test first though, get it working and then make it fit what your app needs to do