开发者

Android, playing sound in soundpool

开发者 https://www.devze.com 2023-04-10 22:40 出处:网络
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 phon

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!


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号