I have spent quite a bit of time researching this online. However, I can't manage to get my Asynctask to load SoundPool sounds in the background. I have 54 sounds, and I load them like this:
int selectHello[] = new int[4];
selectHello[0] = sp.load(this, R.raw.hello1a, 1);
selectHello[1] = sp.load(this, R.raw.hello2a, 1);
selectHello[2] = sp.load(this, R.raw.hello3a, 1);
selectHello[3] = sp.load(this, R.raw.hello4a, 1);
//and so on, 10 more times with different sounds
I need to load them inside of arrays because I am using a randomizer to randomly choose one out of 4 (or so) after clicking a button. My randomizer looks like this:
private void playSound(int id) {
// TODO Auto-generated method stub
int high = playList[id].length-1;
int randomNum;
do {
randomNum = (int)(Math.random()*(high-0+1))+0;
} while (randomNum == previousNum);
previousNum = randomNum;
sp.play(playList[id][randomNum], 1, 1, 0, 0, 1);
}
I created int playList[][]
which is an array of the loaded arrays (such as selectHello[]
) to make it cleaner/simpler to find which sound I need.
int playList[][];
playList = {selectHello, ...etc};
//And so on, 10 more times
When I use the doInBackground()
method, it allows me to return 1 item, and so I have tried to return a playList[][]
that is an array of the loaded arrays. I have two issues. First, if I were to return playList[][]
, then how could I get my main Activity to get the array? I have researched to find that you can change the UI with onPostExecute()
, and I have seen some ways (that I don't completely understand) to return Strings, but not an array[][]
like mine.
My other question is that once I have loaded the SoundPool sounds, then can another SoundPool read them? I'm not sure if the sounds are actually loaded into the SoundPool itself, or simply created into an integer that is readable when the play()
method is called. If not, then it would seem that I would have to return both a SoundPool and an array for my code to work. If someone could give me some real code examples explaining this stuff, it would be greatly appreciated.
As for my actual code in the doInBackground()
method, it only consists of the code shown in the first and third blocks above, and the creation of a SoundPool. Also, sorry if there is anything obvious that I'm doing wrong/not getting here, because I'm new to Java and this is my first question on StackOverflow. Please let me know if there is any other information you need to better answer this question.
I suggest you create a callback interface and that you implement with you activity and then have an instance of this callback class as a variable in you AsyncClass. The callback can take any parameters you want. This is a common design pattern and is already well explained here:
android asynctask sending callbacks to ui
Your interface will obviously be customized to meet your needs but this is a nice outline for you.