blueprintchris
blueprintchris

Reputation: 1105

Android SoundPool sound playback intermittent

I have several GridView items that play a small .ogg file when they are selected. They are played using the SoundPool class, however this class seems very intermittent - sometimes the sound plays, sometimes it doesn't; there is no pattern to this so I am having trouble figuring out why it's doing it.

Here is my code:

public void playSelectionSound(){
        SoundPool sp = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
        int soundId = sp.load(this, R.raw.char_select, 1);
        sp.play(soundId, 1, 1, 0, 0, 1);
    }

Upvotes: 1

Views: 164

Answers (2)

blueprintchris
blueprintchris

Reputation: 1105

I eventually resorted to switching to MediaPlayer instead of SoundPool:

MediaPlayer mp = MediaPlayer.create(this, R.raw.char_select); //open media player
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();
            }
        });
        mp.start(); //play the sound

Works everytime.

Upvotes: 1

Mobile Developer
Mobile Developer

Reputation: 211

You shouldn't try to play it immediately after the load since the load can take time. Instead, you should use SoundPool.OnLoadCompleteListener() and play it in that callback. Here you can be sure that soundpool has loaded successfully.

Upvotes: 0

Related Questions