Not able to achieve Gapless audio looping so far on Android

后端 未结 9 1909
走了就别回头了
走了就别回头了 2020-11-28 06:05

I have tried almost every method but I\'ve failed to achieve gapless audio playback between looping a single track with a duration of 10-15 seconds.

Steps I\'ve trie

9条回答
  •  忘掉有多难
    2020-11-28 06:56

    Something like this should work. Keep two copies of the same file in the res.raw directory. Please note that this is just a POC and not an optimized code. I just tested this out and it is working as intended. Let me know what you think.

    public class MainActivity extends Activity {
    MediaPlayer mp1;
    MediaPlayer mp2;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mp1 = MediaPlayer.create(MainActivity.this, R.raw.demo);
        mp2 = MediaPlayer.create(MainActivity.this, R.raw.demo2);
    
        mp1.start();
    
        Thread thread = new Thread(new Runnable() {
    
            @Override
            public void run() {
                int duration = mp1.getDuration();
                while (mp1.isPlaying() || mp2.isPlaying()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    duration = duration - 100;
                    if (duration < 1000) {
                        if (mp1.isPlaying()) {
                            mp2.start();
                            mp1.reset();
                            mp1 = MediaPlayer.create(MainActivity.this,
                                    R.raw.demo);
                            duration = mp2.getDuration();
    
                        } else {
                            mp1.start();
                            mp2.reset();
                            mp2 = MediaPlayer.create(MainActivity.this,
                                    R.raw.demo2);
                            duration = mp1.getDuration();
                        }
                    }
                }
            }
    
        });
    
        thread.start();
    }
    }
    

提交回复
热议问题