MediaPlayer vs SoundPool for only 1 simultaneous stream

扶醉桌前 提交于 2019-12-08 03:47:35

问题


I'm working on a game in which one single sound is played each time the phone is shaked. Does it make sense to use a SoundPool and load sounds in the onCreate of my activity, or is it ok to create a mediaplayer each time, as shown below:

private void onShake() {
    MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);   
    mp.start();
}

My guess is that SoundPool is better because the sounds are loaded only once. Am I right?

Thanks

Julien


回答1:


As expected, SoundPool is much faster...




回答2:


You can create the mediaPlayer outside the onShake method, and then reset and start it on every shake:

MediaPlayer mp= MediaPlayer.create(this, whipSound[currentWhip][force]);
...
private void onShake() {
    mp.reset();
    mp.start();
}

//or

private void onShake() {
   try {
        mp.stop();
        mp.prepare();
    } catch (IllegalStateException e) { /* Ignore */
    } catch (IOException e) {/* Ignore */ }
   try { 
        mp.start(); 
    } catch (IllegalStateException e) {
        Log.e(TAG, "MediaPlayer failed ", e);
   }
}


来源:https://stackoverflow.com/questions/5338312/mediaplayer-vs-soundpool-for-only-1-simultaneous-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!