I've made a method to play sounds in mp3 format (max file size 145kb). When an event happens in the game I just send the file to this method. It creates a new mediaplayer instance whenever it is called, then releases that instance on completion. My problem is that with both the emulator and my phone, when I play 2 sounds near simultaneously, the sounds either skip (like a scratched CD), or one sound doesn't play at all, or sometimes it actually works.
Is a thread getting overloaded or something? I have a Samsung galaxy s3. Should I use soundpool instead? I've heard it has its own problems
public class MediaSimultaneous {
private MediaPlayer[] mediaPlayerArray = new MediaPlayer[10];
private AudioManager mAudioManager;
int playerNum = -1; // Array index of the player instance.
public void playSound(Context context, int audioId) {
if (mAudioManager == null) {
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
playerNum += 1;
mediaPlayerArray[playerNum] = MediaPlayer.create(context, audioId);
mediaPlayerArray[playerNum].setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
mediaPlayerArray[playerNum] = null;
playerNum -= 1;
if (playerNum <= 0) {
playerNum = 0;
}
}
});
}
});
}