Example usage for android.media MediaPlayer.OnCompletionListener MediaPlayer.OnCompletionListener

List of usage examples for android.media MediaPlayer.OnCompletionListener MediaPlayer.OnCompletionListener

Introduction

In this page you can find the example usage for android.media MediaPlayer.OnCompletionListener MediaPlayer.OnCompletionListener.

Prototype

MediaPlayer.OnCompletionListener

Source Link

Usage

From source file:org.FrancoisDescamps.CatPlayer.MusicService.java

public void playMusic(final String pathToMusic) {
    //register receiver
    IntentFilter receiverFilter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
    HeadphonesUnplugReceiver receiver = new HeadphonesUnplugReceiver();
    registerReceiver(receiver, receiverFilter);

    if (mp != null) {
        mp.stop();//from  w  w  w  .  java 2s. c  o m
        mp = null;
    }

    try {
        mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mp.setDataSource(pathToMusic);
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        /*NOP*/
    }

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            switch (repeat) {
            case 0: // Lecture en boucle dsactive
                /* NOP */
                break;
            case 1: // Lecture en boucle d'une seule musique
                playMusic(pathToMusic);
                break;
            case 2: // Lecture en boucle de toutes les musiques
                if (positionOfInitialMusic + cpt + 1 == queu.size()) {
                    cpt = 0;
                    positionOfInitialMusic = 0;
                } else {
                    cpt++;
                }
                playMusic(queu.get(positionOfInitialMusic + cpt).getPath());
                break;
            }

            currentTitle = properties[0][positionOfInitialMusic + cpt];
            currentAlbum = properties[1][positionOfInitialMusic + cpt];
            currentArtist = properties[2][positionOfInitialMusic + cpt];
            currentPath = properties[3][positionOfInitialMusic + cpt];

            musicAsChanged = true;
            MainActivity.notifyOtherMusicStarted();
            buildNotification(true);

            //save "cpt"
            editor = preferences.edit();
            editor.putInt("cpt", cpt);

            if (Build.VERSION.SDK_INT < 9) {
                editor.commit();
            } else {
                editor.apply();
            }
        }
    });
}