问题
I am trying to load a sound from android.
The sound is under res/raw/myownsound.wav
.
I know that I can already load the sound using:
soundPool.load(context, R.raw.myownsound, 1)
For customization purposes, I would like to load it using:
soundPool.load("res/raw/myownsound", 1)
... but I get the following error : error loading res/raw/myownsound
.
I also tried the following :
soundPool.loadSound("android.resource://upg.GraphismeBase/raw/myownsound", 1)
.. but I get an error as well : error loading android.resource://upg.GraphismeBase/raw/myownsound
What is the correct way of using soundPool.load(path, priority) ?
回答1:
Create a folder structure in your project
/assets/sounds/data/
Then copy your wav file there.
// Declare globally if needed
int mySoundId;
SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0 );
AssetManager am = this.getAssets();
//Use in whatever method is used to load the sounds
try {
mySoundId = soundPool.load(am.openFd("sounds/data/myownsound"), 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
May try this (not sure its working) :
SoundPool mySoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
int myAudioFile = getResId("claps", R.raw.class);
try{
mySoundPool.load(context.getActivity(),myAudioFile,1);
} catch (Exception e){
message = String.valueOf(e);
}
public static int getResId(String variableName, Class<?> c) {
Field field = null;
int resId = 0;
try {
field = c.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
回答2:
Simple working way of doing so with a context named mContext
.
It loads the resource by name by getting the identifier id at run-time.
int sound_id = mContext.getResources().getIdentifier("myownsound", "raw",
mContext.getPackageName());
soundPool.load(mContext, sound_id, 1);
It also works to load drawables or xml files, by replacing "raw"
by "drawable"
or "xml"
for example.
来源:https://stackoverflow.com/questions/12094370/android-soundpool-loadstring-path-int-priority