Ryan
Ryan

Reputation: 10049

Android, playing sound in soundpool

I downloaded some code which instead of playing my sound in my local class calls another class to play the sound, the only problem I am having is it is not allowing me to use my volume keys on my phone to adjust the volume while my old code in my local class allowed me to do it.

In the old way, the local class had this code:

    AudioManager mgr = (AudioManager) GameScreen_bugfix.this.getSystemService(Context.AUDIO_SERVICE);
    float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
    float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    float volume = streamVolumeCurrent / streamVolumeMax;
soundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0,1f);

The new code looks like this:

public static void playSound(int index,float speed) 
    { 
             float streamVolume;
            try {
                streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed);
            } catch (Exception e) {
                e.printStackTrace();
                //Log.v("THE ERROR",  mSoundPoolMap+" "+index);
            } 


    }

so I tried to change it like this:

        AudioManager mgr = (AudioManager) SoundManager.getSystemService(Context.AUDIO_SERVICE);
float streamVolumeCurrent = mgr
        .getStreamVolume(AudioManager.STREAM_MUSIC);
float streamVolumeMax = mgr
        .getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float volume = streamVolumeCurrent / streamVolumeMax;

But this getSystemService gets highlighted in red and when I mouseover it it says:

The method getSystemService(String) is undefined for the type SoundManager

What to do? Thanks!

Upvotes: 1

Views: 4030

Answers (2)

dsandler
dsandler

Reputation: 2481

Actually, if what you want is for the hardware volume keys to adjust the media stream instead of the ringtone stream, you'll want to request that using http://developer.android.com/reference/android/app/Activity.html#setVolumeControlStream(int):

@Override
public void onStart() {
    super.onStart();
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
}

Upvotes: 5

slayton
slayton

Reputation: 20319

If you want to play your sound at the System defined sound level change this:

mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, speed);

to this:

mSoundPool.play(mSoundPoolMap.get(index), 1, 1, 1, 0, speed);

The volume level you pass to play is bound between 0 and 1. It represents a percentage of the system volume to play the sound at. So a value of .5 would play at 50% of the system volume level.

Upvotes: 5

Related Questions