views:

23

answers:

0

Hello! I've created an app that uses MediaPlayer to play a random (short) sound when a button is clicked. The sounds are played correctly on android devices < 2.2. This is the code responsible for playing sounds.

r = new Random();
sounds = new ArrayList<MediaPlayer>();
sounds.add(MediaPlayer.create(this, R.raw.sound1));
sounds.add(MediaPlayer.create(this, R.raw.sound2));
sounds.add(MediaPlayer.create(this, R.raw.sound3));
sounds.add(MediaPlayer.create(this, R.raw.sound4));
sounds.add(MediaPlayer.create(this, R.raw.sound5));

theButton.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
        playSound();
    }
});

private void playSound() {
    Thread thread = new Thread() {
        public void run() {
            MediaPlayer soundPlayer = sounds.get(r.nextInt(sounds.size()));
            while (soundPlayer.isPlaying())
            {
                soundPlayer = sounds.get(r.nextInt(sounds.size()));
            }
            soundPlayer.seekTo(0);
            soundPlayer.start();
        }
    };
    thread.start();
}

The sounds are all .wav files. I tried converting them to .mp3, but then they wouldn't play at all. Am I doing something extremely wrong, or is the MediaPlayer in 2.2 buggy? Anyone else had this problem and know of a fix? Keep in mind that the sounds are played normally on all other devices with an android version below 2.2.