使用SoundPool的无缝循环

时间:2013-12-14 15:05:18

标签: android loops media-player soundpool

我想使用MediaPlayer循环播放此曲目,但它最终会产生这种奇怪的毛刺噪音,该曲目似乎在Audacity中工作正常并使用.OGG,我尝试使用SoundPool但我似乎无法工作

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 个答案:

答案 0 :(得分:2)

你需要搬家:

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

进入onLoadComplete处理程序,否则SoundPool会在实际加载之前尝试播放声音。所以像这样:

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);
    }
});

注意:传递给onLoadComplete处理程序的sampleId是加载的soundId

此外,在SoundPool.play(...)中,您将循环标志设置为0,这意味着永远不会循环。如果您希望声音循环,则需要为-1:

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

希望有所帮助。