0

Okay, I've searched all over and done a bunch of reading and I see now what I'm doing wrong with the below code, especially the concern of a memory leak in doing what I'm attempting to do. But, I'm not quite sure how to do this in a different way. Here's the code:

public class SoundPlayer extends Activity {

private String sound;
private SoundPool soundPool;
private float fSpeed = 1;
private int resID;

public SoundPlayer(String s) {
    sound = s;
}

public SoundPlayer(String s, float f) {
    sound = s;
    fSpeed = f;
}

public void playSound() {
    resID = WorkoutStopwatch.getResources().getIdentifier(sound, "raw", "com.blueflamesys.workoutstopwatch");
    AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = streamVolumeCurrent / streamVolumeMax;

    soundPool.play(resID, volume, volume, 1, 0, fSpeed);
}
}

I'm trying to create an activity (although, after some of the reading I've seen, I think I just need a class and not an activity) to play a sound. This sound will be one of a number of raw files, hence the resID variable setting, and the error I get trying to call getResources() from a non-static method. The refactored class looks like this:

public class SoundPlayer extends {

private SoundPool soundPool;
private float fSpeed = 1;
private int resID;

public SoundPlayer(int r) {
    resID = r;
}

public SoundPlayer(int r, float f) {
    resID = r;
    fSpeed = f;
}

public void playSound() {       
    soundPool.play(resID, 1, 1, 1, 0, fSpeed);
    }
}

Since there's multiple sounds that I'd prefer to address by a String I guess the best thing to do would be to create a hashmap with the key as a string representing the sound and the value as the int resID? Although doing this makes a mess out of the main application code. I guess it doesn't really matter, but I was wondering if this is the right approach, or if there's a better way to do this.

4

0 回答 0