Android Soundpool Load(String path, int priority)

Mikaël Mayer picture Mikaël Mayer · Aug 23, 2012 · Viewed 9.5k times · Source

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

Answer

Alexis C. picture Alexis C. · Aug 23, 2012

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;
}