-3

enter image description here

i am a beginner .i am trying to play sound track using buttons in code but when i am running the app,app is not running.it is showing open app again and again an d when i opens it it shows close app.in log cat it is showing runtime exception saying FATAL EXCEPTION: main/java.lang.RuntimeException: Unable to start activity ComponentInfo{com.devlopers.colourplay/com.devlopers.colourplay.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.SoundPool.load(android.content.Context, int, int)' on if anyone know please help me outenter image description here

vijay
  • 1

1 Answers1

-1

Check if you are initialising soundPool in the right way,

if (Build.VERSION.SDK_INT >= 21 ) {

           AudioAttributes audioAttrib = new AudioAttributes.Builder()
                   .setUsage(AudioAttributes.USAGE_GAME)
                   .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                   .build();

           SoundPool.Builder builder= new SoundPool.Builder();
           builder.setAudioAttributes(audioAttrib).setMaxStreams(MAX_STREAMS);

           this.soundPool = builder.build();
       }
       // for Android SDK < 21
       else {
           // SoundPool(int maxStreams, int streamType, int srcQuality)
           this.soundPool = new SoundPool(MAX_STREAMS,          AudioManager.STREAM_MUSIC, 0);
       }

To check if sound pool is loaded or not:

// When Sound Pool load complete.
       this.soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
           @Override
           public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
               loaded = true;
           }
       });

Use "loaded" flag to play the sound. if true then only call for "play"

For detailed reference : https://o7planning.org/en/10523/playing-sound-effects-in-android-with-soundpool

Gaurav Bansal
  • 604
  • 5
  • 11