0

I want loop play a music without gap

At first. I used .islooping but There was a gap between the music

Then I found a way to gapless between the music.

But I can't make them loop.

Please solve this problem

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val music1 = MediaPlayer.create(this, R.raw.sound1)
        val music2 = MediaPlayer.create(this, R.raw.sound1)

        val musicBtn: ImageButton = findViewById(R.id.button)
        musicBtn.setOnClickListener {
            if (music1.isPlaying or music2.isPlaying) {
                music1.pause()
                music2.pause()
            } else {
                music1.start()
                music1.setNextMediaPlayer(music2)
            }
        }

    }
}

I tried using Timer.

However, there was an error before the second music was played.

enter image description here

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var timer = Timer()
        val fire1 = MediaPlayer.create(this, R.raw.fire1)
        val fire2 = MediaPlayer.create(this, R.raw.fire2)
        val fireVol: SeekBar = findViewById(R.id.fireseek)
        fireVol.visibility = View.INVISIBLE


        val rainBtn4: ImageButton = findViewById(R.id.button)
        rainBtn4.setOnClickListener {
            val TT : TimerTask = object : TimerTask() {
                override fun run() {
                    fire1.start()
                    fire1.setNextMediaPlayer(fire2)
                }
            }
            if (fireVol.isVisible) {
                timer.cancel()
                timer = Timer()
                fire1.pause()
                fire2.pause()
                fireVol.visibility = View.INVISIBLE

            } else {
                timer.schedule(TT, 0,100)
                fireVol.visibility = View.VISIBLE
            }
        }
    }
}
  • Look for a good answer here https://stackoverflow.com/questions/26274182/not-able-to-achieve-gapless-audio-looping-so-far-on-android – Joe Vienneau Jan 21 '22 at 22:51

1 Answers1

0

Note: This might not be a good approach but it works. You can add

setOnCompletionListener

to one of the media players and start the other one in that. Like this;

val btnPlay = findViewById(R.id.btnPlay)

    val mediaPlayer = MediaPlayer.create(this, R.raw.music_one)
    val mediaPlayer2 = MediaPlayer.create(this, R.raw.music_two)

    btnPlay.setOnClickListener { mediaPlayer.start() }
    mediaPlayer.setOnCompletionListener { mediaPlayer2.start() }
Muaz
  • 71
  • 5