Tuesday 20 August 2013

Use String in SoundPool play

Use String in SoundPool play

I'm using SoundPool for my android app. I load about 75 one- to
three-second sounds into the pool in my main activity and then reference
them from other activities using the Sound method which looks like this:
public void Sound(int s){
AudioManager audioManager = (AudioManager)
getSystemService(AUDIO_SERVICE);
float volume = (float)
audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
MainActivity.spool.play(s, volume, volume, 1, 0, 1f);
};
s is the integer I define in the MainActivity class, for example:
static int sound_e;
and then pass into the Sound method like this:
Sound(sound_e);
I would like to be able to define a string like this:
String letter_sound = "MainActivity.sound_" + currentLetter;
//Example value of this string would be MainActivity.sound_a
And then pass that string into Sound as an integer. This is to avoid 26 if
statements, which I did for the numbers like this:
if (randomNum == 1) {Log.v(TAG, "Sound playing for: " + randomNum);
Sound(MainActivity.sound_1);}
else if (randomNum == 2) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_2);}
else if (randomNum == 3) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_3);}
else if (randomNum == 4) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_4);}
else if (randomNum == 5) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_5);}
else if (randomNum == 6) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_6);}
else if (randomNum == 7) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_7);}
else if (randomNum == 8) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_8);}
else if (randomNum == 9) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_9);}
else if (randomNum == 10) {Log.v(TAG, "Sound playing for: " +
randomNum); Sound(MainActivity.sound_10);}
else Log.v(TAG, "None of the ifs are true. randomNum: " + randomNum);
I didn't see in the android documentation any way to pass string values
into the SoundPool play, just integers. Thanks for helping me figure out
what I'm missing!

No comments:

Post a Comment