0

I'm having trouble offloading tasks from the main Activities OnCreate method onto another class to do the heavy lifting.

When I try to call getSystemService from the non-Activity class an exception is thrown.

Any help would be greatly appreciated :)

public void playSound() {
    SoundPool soundPool;
    int soundID;
    final boolean loaded = false;

    soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        public void onLoadComplete(SoundPool soundPool, int sampleId,
                int status) {
            loaded = true;
        }
    });
    soundID = soundPool.load(getContext(), R.raw.voice, 1);
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    float actualVolume = (float) audioManager
            .getStreamVolume(AudioManager.STREAM_MUSIC);
    float maxVolume = (float) audioManager
            .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = actualVolume / maxVolume;
    // Is the sound loaded already?
    if (loaded) {
        soundPool.play(soundID, volume, volume, 1, 0, 1f);
        Log.e("Test", "Played sound");
    }
}
4

1 回答 1

1

试试下面的,

    public void playSound() {
SoundPool soundPool;
int soundID;
final boolean loaded = false;

soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    public void onLoadComplete(SoundPool soundPool, int sampleId,
            int status) {
        loaded = true;
    }
});
soundID = soundPool.load(getContext(), R.raw.voice, 1);
AudioManager audioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
float actualVolume = (float) audioManager
        .getStreamVolume(AudioManager.STREAM_MUSIC);
float maxVolume = (float) audioManager
        .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = actualVolume / maxVolume;
// Is the sound loaded already?
if (loaded) {
    soundPool.play(soundID, volume, volume, 1, 0, 1f);
    Log.e("Test", "Played sound");
}

}

于 2013-06-14T13:11:03.930 回答