1

I'm really new at java and android and I'm trying to play some sound after a button is pressed. I searched a lot and tried this:

//package and imports

public class Simulador extends Activity {
int contador;
Button somar;

SoundPool som;
boolean loaded;
int comeu, comprou;

protected void onCreate(Bundle primeiroBundle) {
    super.onCreate(primeiroBundle);
    setContentView(R.layout.activity_primeira_atividade);
    contador = 0;
    somar = (Button) findViewById(R.id.som);
    som = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);

    //I removed the whole part from the other button,
    //since it's basically the same. So that's why I need to set maxStreams to 2.

    comeu = som.load(this, R.raw.comeu, 1);
    som.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        public void onLoadComplete(SoundPool som, int sampleId, int status){
            loaded = true;
        }
    });

    somar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (loaded) {
                som.play(comprou, 1, 1, 1, 0, 1f);
            }
            contador += 5;
            }
        }
    });
}

protected void onPause() {
    super.onPause();
    som.release();
    som = null;
}
}

My code is working as it should, but I got the follwing warning:

SoundPool(int, int, int)' is deprecated

So I came here to see how to solve and got this:

This constructor was deprecated in API level 21. use SoundPool.Builder instead to create and configure a SoundPool instance

So I went here but couldn't addapt my code to this new constructor, even reading the reference. Does anyone know how to solve this?

rado
  • 5,720
  • 5
  • 29
  • 51

1 Answers1

0

I know this question is a couple years old and You've probably already solved this, but hopefully this answer can help others.

For those whom are concerned about backwards compatibility in android versions and want to have the best of both worlds, here is a possible implementation that I've done.

In the onCreate() function where you instantiate your SoundPool object, write a logic check for the android version and use the respective constructor.

// For ADK versions 21 (Lollipop) or greater
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
    sounds = new SoundPool.Builder().build();
// Else use older syntax (deprecated with ADK 21)
} else {
    sounds = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
}

Note: this will technically still throw a warning in your IDE for using the deprecated method, but if you are concerned about APKs bellow 21, this may be the best option for you.

After you have instantiated it, simply load your sound files, and play the sound (call the bellow playSound() method in the onClick() listener on your button):

soundId = sounds.load(context, R.raw.sound, 1);

public void playSound() {
    sounds.play(soundId, 1, 1, 1, 0, 1);
}
Matt Strom
  • 698
  • 1
  • 4
  • 23