Example usage for android.media MediaPlayer setOnCompletionListener

List of usage examples for android.media MediaPlayer setOnCompletionListener

Introduction

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

Prototype

public void setOnCompletionListener(OnCompletionListener listener) 

Source Link

Document

Register a callback to be invoked when the end of a media source has been reached during playback.

Usage

From source file:de.azapps.mirakel.helper.TaskDialogHelpers.java

public static void playbackFile(final Activity context, final FileMirakel file, final boolean loud) {
    final MediaPlayer mPlayer = new MediaPlayer();
    final AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
    if (!loud) {/*  w  w w . j  a v  a 2 s.c  o m*/
        am.setSpeakerphoneOn(false);
        am.setMode(AudioManager.MODE_IN_CALL);
        context.setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
    }
    try {
        mPlayer.reset();
        if (!loud) {
            mPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        }
        mPlayer.setDataSource(file.getFileStream(context).getFD());
        mPlayer.prepare();
        mPlayer.start();
        mPlayer.setOnCompletionListener(new OnCompletionListener() {
            @Override
            public void onCompletion(final MediaPlayer mp) {
                audio_playback_dialog.dismiss();
            }
        });
        am.setMode(AudioManager.MODE_NORMAL);
        audio_playback_playing = true;
    } catch (final IOException e) {
        Log.e(TAG, "prepare() failed");
    }
    audio_playback_dialog = new AlertDialog.Builder(context).setTitle(R.string.audio_playback_title)
            .setPositiveButton(R.string.audio_playback_pause, null)
            .setNegativeButton(R.string.audio_playback_stop, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, final int which) {
                    mPlayer.release();
                }
            }).setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(final DialogInterface dialog) {
                    mPlayer.release();
                    dialog.cancel();
                }
            }).create();
    audio_playback_dialog.setOnShowListener(new OnShowListener() {
        @Override
        public void onShow(final DialogInterface dialog) {
            final Button button = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View v) {
                    if (audio_playback_playing) {
                        button.setText(R.string.audio_playback_play);
                        mPlayer.pause();
                        audio_playback_playing = false;
                    } else {
                        button.setText(R.string.audio_playback_pause);
                        mPlayer.start();
                        audio_playback_playing = true;
                    }
                }
            });
        }
    });
    audio_playback_dialog.show();
}

From source file:com.google.android.apps.forscience.whistlepunk.metadata.TriggerHelper.java

public void doAudioAlert(Context context) {
    // Use a throttler to keep this from interrupting itself too much.
    if (System.currentTimeMillis() - mLastAudioMs < THROTTLE_LIMIT_MS) {
        return;/*from  www  .jav  a2s .  c  o  m*/
    }
    mLastAudioMs = System.currentTimeMillis();
    final MediaPlayer mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {
        mediaPlayer.setDataSource(context, mNotification);
        mediaPlayer.setOnPreparedListener(MEDIA_PLAYER_ON_PREPARED_LISTENER);
        mediaPlayer.setOnCompletionListener(MEDIA_PLAYER_COMPLETION_LISTENER);
        // Don't prepare the mediaplayer on the UI thread! That's asking for trouble.
        mediaPlayer.prepareAsync();
    } catch (IOException e) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "error getting notification sound");
        }
    }
}

From source file:se.eliga.aves.songs.BirdSpeciesXenoCantoPlayerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.audio_player_layout, container, false);

    setHasOptionsMenu(true);/*from  w  w  w.j a  v  a  2 s.  c o  m*/

    mediaPlayer = new MediaPlayer();
    mediaController = new MediaController(getActivity(), false);
    mediaController.setMediaPlayer(this);
    mediaController.setAnchorView(view);

    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            if (what == -38) {
                return true; //not pretty.. http://stackoverflow.com/questions/15205855/error-19-0-mediaplayer/15206308#15206308
            } else {
                return false;
            }
        }
    });

    mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
            progressBar.setProgress(percent);
        }
    });
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            handler.post(new Runnable() {
                public void run() {
                    progressBar.setVisibility(ProgressBar.GONE);
                    if (mediaController != null) {
                        mediaController.show(0);
                    }
                    if (mediaPlayer != null) {
                        try {
                            mediaPlayer.start();
                        } catch (Exception e) {
                            Log.d(TAG, "Could not start mediaplayer", e);
                        }
                    }
                }
            });
        }
    });
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            if (audioAutoNext.isChecked()) {
                int count = getListAdapter().getCount();
                XenoCantoAudio nextAudio;
                if (currentPosition < (count - 1)) {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(++currentPosition);
                } else {
                    nextAudio = (XenoCantoAudio) getListAdapter().getItem(0);
                }
                initiatePlay(nextAudio);
            }
        }
    });
    loadBird(getCurrentBird());
    return view;
}

From source file:me.tylerbwong.pokebase.gui.activities.PokemonProfileActivity.java

private void playAudio() {
    final MediaPlayer player = MediaPlayer.create(this,
            getResources().getIdentifier(AUDIO + pokemonId, RAW, getPackageName()));
    player.setOnCompletionListener(mediaPlayer -> player.release());
    player.start();/*from   www.  j  ava  2 s . c  o  m*/
    Toast.makeText(this, getString(R.string.sound_played), Toast.LENGTH_SHORT).show();
}

From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java

private MediaPlayer initAudibleMediaPlayer(String audiblePath, int type) throws IOException {
    MediaPlayer mp = mMediaPlayers.get(type);
    if (mp == null) {
        mp = new MediaPlayer();
        mMediaPlayers.put(type, mp);//from   w  ww  .  j  a v a 2s. c  o m
    } else {
        mp.reset();
    }
    mp.setDataSource(audiblePath);
    mp.prepare();
    mp.setOnCompletionListener(mPlayCompletionListener);
    return mp;
}

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();//  ww w . j a  v  a 2 s  . 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();
            }
        }
    });
}

From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java

private MediaPlayer initAudibleMediaPlayer(AssetFileDescriptor afd, int type) throws IOException {
    MediaPlayer mp = mMediaPlayers.get(type);
    if (mp == null) {
        mp = new MediaPlayer();
        mMediaPlayers.put(type, mp);/*from   ww w  .j  a va2  s  .  com*/
    } else {
        mp.reset();
    }
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mp.prepare();
    mp.setOnCompletionListener(mPlayCompletionListener);
    return mp;
}

From source file:edu.northwestern.cbits.activitydetector.app.MainActivity.java

private void UpdateGUI() {
    i++;/*  ww  w. ja  v a  2 s.c  om*/

    final MainActivity me = this;

    // Runs once a second
    mHandler.post(new Runnable() {
        public void run() {
            Log.d(getString(R.string.app_name), ActivityRecognitionIntentService.ACTIVITY_NAME);
            nameView.setText(
                    ActivityRecognitionIntentService.ACTIVITY_NAME + " " + System.currentTimeMillis() / 1000);

            //setting up tone for on_foot
            Uri defaultRingtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            MediaPlayer mediaPlayer = new MediaPlayer();

            try {
                mediaPlayer.setDataSource(me, defaultRingtoneUri);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                mediaPlayer.prepare();
                mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        mp.release();
                    }
                });

                if (ActivityRecognitionIntentService.ACTIVITY_NAME == "on_foot") {
                    mediaPlayer.start();
                } else {
                    mediaPlayer.release();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            ;
        }
    });
}

From source file:net.wespot.pim.view.InqImageDetailFragment.java

public void playPauseButton() {
    if (status == PAUSE) {
        playPauseButton//from w  w w  .  jav  a  2  s . com
                .setImageDrawable(getActivity().getResources().getDrawable(android.R.drawable.ic_media_pause));

        status = PLAYING;
        mediaPlayer.start();

        finalTime = mediaPlayer.getDuration();
        startTime = mediaPlayer.getCurrentPosition();
        if (oneTimeOnly == 0) {
            seekbar.setMax((int) finalTime);
            oneTimeOnly = 1;
        }
        seekbar.setProgress((int) startTime);
        playHandler.postDelayed(UpdateSongTime, 100);
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                status = PAUSE;
                playPauseButton.setImageDrawable(
                        getActivity().getResources().getDrawable(android.R.drawable.ic_media_play));
            }
        });
    } else {
        playPauseButton
                .setImageDrawable(getActivity().getResources().getDrawable(android.R.drawable.ic_media_play));
        status = PAUSE;
        mediaPlayer.pause();
    }
}

From source file:com.lithiumli.fiction.PlaybackService.java

private void prepareNext() {
    int position = mQueue.getCurrentPosition();

    if (position >= mQueue.getCount() - 1) {
        // TODO: repeat modes
        return;/*w  w w .j a va  2 s.  c om*/
    }

    Song song = mQueue.getItem(position + 1);
    try {
        mNextPlayer = new MediaPlayer();
        mNextPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mNextPlayer.setDataSource(getApplicationContext(), song.getUri());
        mNextPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer player) {
                if (mMediaPlayer == null) {
                } else {
                    mMediaPlayer.setNextMediaPlayer(player);
                    mMediaPlayer.setOnCompletionListener(PlaybackService.this);
                    player.setOnCompletionListener(PlaybackService.this);
                }
            }
        });
        mNextPlayer.prepareAsync();
    } catch (IOException e) {
    }
}