4

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) ?

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101

2 Answers2

6

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;
}
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
5

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.

Mikaël Mayer
  • 10,425
  • 6
  • 64
  • 101