1

I'm trying to do something with Uri that feels like it should be relatively simple but I haven't found a straight answer anywhere, maybe what I'm trying to do doesn't require the use of Uri.

In my project's res/raw folder I have a bunch of .wav files that have identical names but end in different numbers:

res/
raw/
sample_0.wav
sample_1.wav
sample_2.wav
sample_3.wav

I want to load one of them in a SoundPool with something like this:

Soundpool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);

public void playSound(int i, Activity a){
spPath = Uri.parse("android.resource://jgjp.com.appname/raw/R.raw.sample_"+i);
int spID = sp.load(a, spPath, 1);
sp.play(spID, 1, 1, 1, 0, 1);
}

I'm using the Uri object because I want to be able to change the last digit of the resource's file name based on the received argument.

My problem is with the line int spID = sp.load(a, spPath, 1); where it's expecting spPath to be an int rather than a Uri. I know that resource identifiers like R.raw.sample_1 actually return int values, how do I get the corresponding int from the Uri class after I've set it with Uri.parse()?

Checking through the android documentation for the Uri class hasn't yielded much and while I can find plenty of tutorials about setting the Uri I can't find much about how to use it.

JGJP
  • 33
  • 4
  • http://developer.android.com/intl/zh-cn/reference/android/media/SoundPool.html#load%28java.lang.String,%20int%29 load(uri.toString(), 1) – usil Sep 17 '15 at 03:22
  • Thanks for the quick reply, any reason why it doesn't allow you to set the context this way? I wanted playsound() to be a method I could call from another class but I can probably work around this.. – JGJP Sep 17 '15 at 03:36
  • for some reason using the string path without passing in the context gives me a "sample 0 not READY" error message in logcat and no sound is played... I'm using it within my activity java class now and it's not working.. – JGJP Sep 17 '15 at 03:57
  • 1
    possible duplicate of [How to read file from res/raw by name](http://stackoverflow.com/questions/15912825/how-to-read-file-from-res-raw-by-name) – user2413972 Sep 17 '15 at 05:41

1 Answers1

1

You can obtain the numeric ID of your raw resource using Resources.getIdentifier() and then use it in your play function:

int id = getResources().getIdentifier("sample_0", "raw", getPackageName());

user2413972
  • 1,355
  • 2
  • 9
  • 25