开发者社区> 问答> 正文

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

需要在游戏中添加可以同时播放或同时播放的简短声音(例如,爆炸声)。为此,我尝试将队列与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渲染循环中播放简短的叠加声音?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 20:13:30 908 0
1 条回答
写回答
取消 提交回答
  • 看完这篇文章后

    解决方案:我使用了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);
            }
        }
    }
    

    回答来源:Stack Overflow

    2020-03-22 20:14:08
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
360°全景视频播放器的实现原理 立即下载
全景视频的播放及优化 立即下载
3D动画的菜谱式灯光与云渲染 立即下载