Reputation: 86925
I want to initialize MediaPlayer
instances for all of the soundfiles found in res/raw
:
/res/raw/test1.mp3
/res/raw/test2.mp3
/res/raw/testN.mp3
Purpose is to play different samples on a button click, without delays.
List<MediaPlayer> player = new ArrayList<>();
//TODO how to loop properly?
for (Rawfile file : rawfiles) {
pl = MediaPlayer.create(getBaseContext(), R.raw.test1);
player.add(pl);
}
Lateron, if eg button2 is clicked:
player.get(1).start();
Question: how can I get the R.raw.*
files dynamically during initialization of the app?
Update: the following is quite close, but there are 2 problems:
1) If eg only one file "test.mp3" is placed in my /res/raw
folder, the function shows 3 files.
2) How can I then load those files to mediaplayer?
public void listRaw(){
Field[] fields=R.raw.class.getFields();
for(int count=0; count < fields.length; count++){
Log.i("Raw Asset: ", fields[count].getName());
}
}
Result:
I/Raw Asset:: $change
I/Raw Asset:: serialVersionUID
I/Raw Asset:: test
Upvotes: 3
Views: 1727
Reputation: 3852
Though undervoted, this answer from CommonsWare is comprehensive. The best you can do is iterate over the raw fields by reflection. If you find non-resource fields, you should discard them manually (I see you did it in an answer).
One point: putting files in raw
directory is done during development time, and programming the iteration over raw
resources is also done during development time. It's a problem you should solve before compilation, rather than finding out what files you have in run time, that is, you should list the files by name in your code.
Upvotes: 0
Reputation: 86925
For the moment solved as follows, but feels kinda hacky:
public static List<Integer> listRawMediaFiles() {
List<Integer> ids = new ArrayList<>();
for (Field field : R.raw.class.getFields()) {
try {
ids.add(field.getInt(field));
} catch (Exception e) {
//compiled app contains files like '$change' or 'serialVersionUID'
//which are no real media files
}
}
return ids;
}
Upvotes: 3
Reputation: 5339
I Really forget from where i get this, it can be duplicated any way not my code but works perfectly :
private boolean listFiles(String path) {
String [] list;
try {
list = getAssets().list(path);
if (list.length > 0) {
// folder founded
for (String file : list) {
if (!listAssetFiles(path + "/" + file))
return false;
}
} else {
//file founded
}
} catch (IOException e) {
return false;
}
return true;
}
Upvotes: 0