How to play short sounds while swiping pages ?

后端 未结 2 761
庸人自扰
庸人自扰 2020-12-21 06:02

I have problem with ViewPager and can\'t find answer on this site or via a Google search.
How to play short sounds while swiping pages?
How can I change my code, I

相关标签:
2条回答
  • 2020-12-21 06:25

    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

    0 讨论(0)
  • 2020-12-21 06:45

    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.

    0 讨论(0)
提交回复
热议问题