MediaPlayer vs SoundPool for only 1 simultaneous s

2019-05-21 08:47发布

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

2条回答
Root(大扎)
2楼-- · 2019-05-21 09:49

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);
   }
}
查看更多
Ridiculous、
3楼-- · 2019-05-21 09:52

As expected, SoundPool is much faster...

查看更多
登录 后发表回答