0

Need to add short sounds to the game that can play simultaneously or almoust simultaneously (for example, explosive sounds). For this, I tried to use the queue with instances of MediaPlayer:

public class Renderer implements GLSurfaceView.Renderer {
    // queue for alternately playing sounds
    private Queue<MediaPlayer> queue = new LinkedList<>();
    private MediaPlayer player1;
    private MediaPlayer player2;
    private MediaPlayer player3;
    public void onSurfaceCreated(GL10 glUnused, EGLConfig config) {
        player1.setDataSource(context, uri);
        player1.prepareAsync();
        ...
        queue.add(player1);
        queue.add(player2);
        queue.add(player3);
    }
    public void onDrawFrame(GL10 glUnused) {
        if (isExplosion) {
            MediaPlayer currentPlayer = queue.poll(); // retrieve the player from the head of the queue
            if (currentPlayer != null) {
                if (!currentPlayer.isPlaying()) currentPlayer.start();
            queue.add(currentPlayer); // add player to end of queue
            }            
        }
    }
}

But this approach showed poor performance. How to play short superimposed sounds in a OpenGL ES render loop?

alexrnov
  • 2,346
  • 3
  • 18
  • 34

1 Answers1

0

After reading this post

Solution: I used SoundPool:

public class Renderer implements GLSurfaceView.Renderer {
    private SoundPool explosionSound;
    private SparseIntArray soundPoolMap = new SparseIntArray();
    public void onSurfaceChanged(GL10 glUnused, int width, int height) {
        // use three streams for playing sounds
        explosionSound = new SoundPool(3, AudioManager.STREAM_MUSIC, 100);
        soundPoolMap.put(0, explosionSound.load(gameActivity, R.raw.explosion, 0));
    }
    public void onDrawFrame(GL10 glUnused) {
        if(isExplosion) { 
            // play current sound
            explosionSound.play(soundPoolMap.get(0), 1.0f, 1.0f, 0, 0, 1f);
        }
    }
}
alexrnov
  • 2,346
  • 3
  • 18
  • 34