How to play short sounds while swiping pages ?

主宰稳场 提交于 2019-11-29 15:16:43

Use SoundPool. It is specifically designed to play short sounds (esp in games, multimedia apps).

here is a tutorial - http://content.gpwiki.org/index.php/Android:Playing_Sound_Effects_With_SoundPool

An example:

private static final int rId = R.raw.sound;
private int sid=-1;
private boolean loaded = false;
SoundPool soundPool;

private SoundPool.OnLoadCompleteListener listener = 
new SoundPool.OnLoadCompleteListener(){
@Override
public void onLoadComplete(SoundPool soundPool, int sid, int status){ // could check status value here also
  if (this.sid == sid) {
    this.loaded = true;
  }
}
};


public void initSound() {
  soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
  soundPool.setOnLoadCompleteListener(listener);
  this.sid = soundPool.load(getApplicationContext(), rId, 1); 
}

public void SoundPlay() {
  new Thread(new Runnable() {
    @Override
    public void run() {
      if (loaded) {
      soundPool.play(this.sid, 1.0, 1.0, 1, 0, 1f);     
        }
  }).start();
}

So you would add a constructor like:

MyPagerAdapter() {
  initSound();
}

and to play each time in instantiateItem() with SoundPlay();

I have not tested the above code as is, but use similar in my own stuff.

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