Jim Tan
Jim Tan

Reputation: 21

Android SoundPool guide

I just stumbled across this functionality of "SoundPool" that sounded quite cool. But after hours of studying the Android doc and examples, I cannot get anything working. I am not sure if I missed anything at all. Compiler (Android Studio) did not report error. Just when I click a button for playing sound, no sound playing. Please help.

Here are the main codes I came up with.

public class MainActivity extends AppCompatActivity {

    Button btnPlay;
    AudioAttributes audioAttributes;
    SoundPool sp;
    TextView tvNote;


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

        btnPlay = (Button) findViewById(R.id.btnPlay);
        tvNote = (TextView) findViewById(R.id.tvNote);


    }

    public void playClicked(View v) {
        audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .build();
        sp = new SoundPool.Builder()
                .setMaxStreams(4)
                .setAudioAttributes(audioAttributes)
                .build();
        int soundId = sp.load(getApplicationContext(), R.raw.piano_c3, 1);
        sp.play(soundId, 1, 1, 1, 0, 1f);

        tvNote.setText("piano_c3");

    }

Please let me know what I missed. Thanks.

Upvotes: 0

Views: 1792

Answers (1)

Kevin Kurien
Kevin Kurien

Reputation: 842

soundPool.play(soundID,leftVolume,rightVolume,priority,loop,rate);

These are the attributes required to play soundpool

leftVolume,rightVolume,priority are set to 1 which is fine

and rate if 1f which is good too, it means how fast you want to play your sound the higher the number the faster the speed

But you have kept the loop to "0" so it does not play any sound here are what different types of the number mean

0:- play 0 times

1:- play 1 time

-1:- play infinite times in a loop

try changing it to your appropriate settings

Upvotes: 1

Related Questions