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渲染循环中播放短叠加声音?

阅读这篇文章后

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

最新更新