OpenGL ES 渲染循环中的短叠加声音

Short superimposed sounds in a OpenGL ES render loop

需要向可以同时或几乎同时播放的游戏添加短音(例如,爆炸声)。为此,我尝试将队列与 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
            }            
        }
    }
}

但这种方法表现不佳。如何在 OpenGL ES 渲染循环中播放短的叠加声音?

看完这篇post

解决方法: 我用的是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);
        }
    }
}