MediaPlayer onCompletionListener

Another way to create an endless loop, I’m thinking, is by using the onCompletionListener function which seems very convenient.  I would imagine it’s fantastic for creating a playlist of song by tying it up with an array of songs or a set of pointers to songs in a database.  But since I’m looking to call the same fragment repeatedly, my code ends up being somewhat recursive.

The Background constructor looks like this:

Background(Context con) {
context = con;
mp1 = MediaPlayer.create(context, R.raw.neroli2);
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
});

Now the call from the UI is even simpler:

public void play() {
mp1.start();

As unbelievably clean as this code is, it still creates a .31 second gap, which wouldn’t be terrible if this was between tracks, but it’s not seamless yet.

I would be remiss if I didn’t give a shout-out to the folks who created IntelliJ platform.  The prototyping for the setOnCompletionListener was awe inspiring.  Type in “new MediaPlayer.OnCompletionListener” and the rest of the framework is automatically inserted into your code.  I’m still in disbelief it’s that smart.  🙂

 

Comments are closed.