Question

I'm kind of new to java, so bear with me if I've made a very stupid mistake. I am trying to play a sound when a button is clicked on a counter app using SoundPool, but the app crashes when either of the buttons are clicked. No errors show up during compilation. Here's the code.

package com.example.c0unter;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.media.SoundPool;
import android.media.AudioManager;

public class MainActivity extends Activity {

    private int Count=0;
    private SoundPool spool;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button ResetButton = (Button) findViewById(R.id.ResetButton);
        Button CounterButton = (Button) findViewById(R.id.CounterButton);
        final TextView CountText = (TextView) findViewById(R.id.CountText);


         ResetButton.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Sound(R.raw.reset_button);
                Count=0;
                CountText.setText(" " + Count);

            }

        });




     CounterButton.setOnClickListener(new OnClickListener() {

         public void onClick(View v) {
             Sound(R.raw.counter_button);
             Count++;
             CountText.setText(" " +Count);
         }
     });
    }

    public void Sound(int soundID){

          spool.load(this, soundID ,1);
          AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
          float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
          spool.play(soundID, volume, volume, 1, 0, 1f);
    };

}
Was it helpful?

Solution

spool is null. When you call it here:

spool.load(this, soundID ,1);

You will get a nullPointerException. You need to initialise it first before you use it. For example:

spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);

I suggest you also have another look through some of the tutorials like this one as there are some other errors in your code. You have to first load the sounds and get an ID back and then pass that ID to play. You cannot just pass R.raw.reset_button to play, it won't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top