Seamless loop using SoundPool

2.2k views Asked by At

I want to loop this track using MediaPlayer, but it makes this weird glitch noise at the end, The track seemed to work fine in Audacity and it uses .OGG, I tried using SoundPool but I cant seem to that that to work.

SoundPool pool = new SoundPool(1, AudioManager.STREAM_MUSIC,0);
    AssetFileDescriptor lfd =      this.getResourc es().openRawResourceFd(R.raw.dishwasherloop);
    //mediaPlayer = new MediaPlayer();
    try
    {
        //mediaPlayer.setDataSource(lfd.getFileDescriptor(),lfd.getStartOffset(), lfd.getLength());
        //mediaPlayer.prepare();
        //mediaPlayer.start();

        int dish = pool.load(lfd,1);
        pool.play(dish,0.5f,0.5f,1,-1,1.0f);
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
        {
                public void onLoadComplete(SoundPool soundPool, int sampleId,
                          int status) {
                   loaded = true;
               }
         });
         int soundID = soundPool.load(this, R.raw.dishwasherloop, 1);
         soundPool.play(soundID, 0.5f, 0.5f, 1, 0, 1f);
1

There are 1 answers

0
Badgerati On

You need to move:

soundPool.play(soundID, 0.5f, 0.5f, 1, 0, 1f);

into the onLoadComplete handler, otherwise the SoundPool will try to play the sound before it's actually loaded. So something like this:

soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener()
{
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status)
    {
       loaded = true;
       soundPool.play(sampleId, 0.5f, 0.5f, 1, 0, 1f);
    }
});

Note: the sampleId passed to the onLoadComplete handler is the soundId loaded.

Also, within the SoundPool.play(...), you're setting the loop flag to 0, which means never loop. If you wish the sound to loop, this needs to be -1:

soundPool.play(sampleId, 0.5f, 0.5f, 1, -1, 1f);

Hope that helps.