Question

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.

Was it helpful?

Solution 2

Seems there was a problem with the sampling rate of the mp3's that the 2.2 Framework frowned upon. I fixed it by opening up the sounds in a sound editor, resampling them and adding silence to the first and last second of the sounds.

OTHER TIPS

I think you shouldn't create a ArrayList for MediaPlayer. Instead that, you use only a MediaPlayer object and a ArrayList to contain all music resources.

When you next other song, you update only the info of MediaPlayer. For example, Release the previous MediaPlayer object. Create other MediaPlayer object Finally, start this song

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