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:github.daneren2005.dsub.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/*  w  ww . j  a  va2  s  .c om*/
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        String dataSource = file.getPath();
        if (isPartial) {
            if (proxy == null) {
                proxy = new StreamProxy(this);
                proxy.start();
            }
            dataSource = String.format("http://127.0.0.1:%d/%s", proxy.getPort(),
                    URLEncoder.encode(dataSource, Constants.UTF_8));
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadServiceImpl.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        if (start) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);
                        } else {
                            setPlayerState(PAUSED);
                        }
                    }

                    lifecycleSupport.serializeDownloadQueue();
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

@Override
public void onUnbind(long messageId, AudioContentViewControl view) {
    AudioFragment audio = findAudioFragment();
    if (audio != null && audio.getMessageId() == messageId) {
        mAudioControl = null;//from   w ww . j  ava2 s .  c  om
        MediaPlayer player = audio.getPlayer();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                getAudioFragment().seekPlayerTo(0);
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });

        view.setProgressChangeListener(false);
        if (!MessagesProvider.exists(getActivity(), messageId)) {
            resetAudio(view);
        }

        else {
            stopMediaPlayerUpdater();
        }
    }
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial, final boolean isPlaying) {
    final int duration = downloadFile.getSong().getDuration() == null ? 0
            : downloadFile.getSong().getDuration() * 1000;
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            Log.w(TAG, "Error on playing file " + "(" + what + ", " + extra + "): " + downloadFile);
            int pos = getPlayerPosition();
            reset();/*from  w w w .  j a  v a 2  s.  co m*/
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
            } else {
                downloadFile.setPlaying(false);
                doPlay(downloadFile, pos, isPlaying);
                downloadFile.setPlaying(true);
            }
            return true;
        }
    });

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            // Acquire a temporary wakelock, since when we return from
            // this callback the MediaPlayer will release its wakelock
            // and allow the device to go to sleep.
            wakeLock.acquire(30000);

            setPlayerStateCompleted();

            int pos = getPlayerPosition();
            Log.i(TAG, "Ending position " + pos + " of " + duration);
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000)) || nextSetup) {
                playNext();
                postPlayCleanup(downloadFile);
            } else {
                // If file is not completely downloaded, restart the playback from the current position.
                synchronized (DownloadService.this) {
                    if (downloadFile.isWorkDone()) {
                        // Complete was called early even though file is fully buffered
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        downloadFile.setPlaying(false);
                        doPlay(downloadFile, pos, true);
                        downloadFile.setPlaying(true);
                    } else {
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        bufferTask = new BufferTask(downloadFile, pos, true);
                        bufferTask.execute();
                    }
                }
                checkDownloads();
            }
        }
    });
}

From source file:org.kontalk.ui.ComposeMessageFragment.java

private boolean prepareAudio(File audioFile, final AudioContentViewControl view, final long messageId) {
    stopMediaPlayerUpdater();/*  www .jav a  2  s. c o  m*/
    try {
        AudioFragment audio = getAudioFragment();
        final MediaPlayer player = audio.getPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(audioFile.getAbsolutePath());
        player.prepare();

        // prepare was successful
        audio.setMessageId(messageId);
        mAudioControl = view;

        view.prepare(player.getDuration());
        player.seekTo(view.getPosition());
        view.setProgressChangeListener(true);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopMediaPlayerUpdater();
                view.end();
                AudioFragment audio = findAudioFragment();
                if (audio != null)
                    audio.seekPlayerTo(0);
                setAudioStatus(AudioContentView.STATUS_ENDED);
            }
        });
        return true;
    } catch (IOException e) {
        Toast.makeText(getActivity(), R.string.err_file_not_found, Toast.LENGTH_SHORT).show();
        return false;
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

private void setupHandlers(final DownloadFile downloadFile, final boolean isPartial, final boolean isPlaying) {
    final int duration = downloadFile.getSong().getDuration() == null ? 0
            : downloadFile.getSong().getDuration() * 1000;
    mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
            Log.w(TAG, "Error on playing file " + "(" + what + ", " + extra + "): " + downloadFile);
            int pos = getPlayerPosition();
            reset();/*from   www  .j  a  va 2s . com*/
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000))) {
                playNext();
            } else {
                downloadFile.setPlaying(false);
                doPlay(downloadFile, pos, isPlaying);
                downloadFile.setPlaying(true);
            }
            return true;
        }
    });

    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            setPlayerStateCompleted();

            int pos = getPlayerPosition();
            Log.i(TAG, "Ending position " + pos + " of " + duration);
            if (!isPartial || (downloadFile.isWorkDone() && (Math.abs(duration - pos) < 10000)) || nextSetup) {
                playNext();
                postPlayCleanup(downloadFile);
            } else {
                // If file is not completely downloaded, restart the playback from the current position.
                synchronized (DownloadService.this) {
                    if (downloadFile.isWorkDone()) {
                        // Complete was called early even though file is fully buffered
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        downloadFile.setPlaying(false);
                        doPlay(downloadFile, pos, true);
                        downloadFile.setPlaying(true);
                    } else {
                        Log.i(TAG, "Requesting restart from " + pos + " of " + duration);
                        reset();
                        bufferTask = new BufferTask(downloadFile, pos, true);
                        bufferTask.execute();
                    }
                }
                checkDownloads();
            }
        }
    });
}

From source file:github.daneren2005.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/*from   w w  w  .  j a va2s .  c o m*/
        downloadFile.setPlaying(true);
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        boolean isPartial = file.equals(downloadFile.getPartialFile());
        downloadFile.updateModificationDate();

        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }
        String dataSource = file.getAbsolutePath();
        if (isPartial && !Util.isOffline(this)) {
            if (proxy == null) {
                proxy = new BufferProxy(this);
                proxy.start();
            }
            proxy.setBufferFile(downloadFile);
            dataSource = proxy.getPrivateAddress(dataSource);
            Log.i(TAG, "Data Source: " + dataSource);
        } else if (proxy != null) {
            proxy.stop();
            proxy = null;
        }
        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}

From source file:github.popeen.dsub.service.DownloadService.java

private synchronized void doPlay(final DownloadFile downloadFile, final int position, final boolean start) {
    try {/* w  w w.  java  2  s  . c o m*/
        subtractPosition = 0;
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.setOnPreparedListener(null);
        mediaPlayer.setOnErrorListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        try {
            mediaPlayer.setAudioSessionId(audioSessionId);
        } catch (Throwable e) {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        }

        String dataSource;
        boolean isPartial = false;
        if (downloadFile.isStream()) {
            dataSource = downloadFile.getStream();
            Log.i(TAG, "Data Source: " + dataSource);
        } else {
            downloadFile.setPlaying(true);
            final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                    : downloadFile.getPartialFile();
            isPartial = file.equals(downloadFile.getPartialFile());
            downloadFile.updateModificationDate();

            dataSource = file.getAbsolutePath();
            if (isPartial && !Util.isOffline(this)) {
                if (proxy == null) {
                    proxy = new BufferProxy(this);
                    proxy.start();
                }
                proxy.setBufferFile(downloadFile);
                dataSource = proxy.getPrivateAddress(dataSource);
                Log.i(TAG, "Data Source: " + dataSource);
            } else if (proxy != null) {
                proxy.stop();
                proxy = null;
            }
        }

        mediaPlayer.setDataSource(dataSource);
        setPlayerState(PREPARING);

        mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
            public void onBufferingUpdate(MediaPlayer mp, int percent) {
                Log.i(TAG, "Buffered " + percent + "%");
                if (percent == 100) {
                    mediaPlayer.setOnBufferingUpdateListener(null);
                }
            }
        });

        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            public void onPrepared(MediaPlayer mediaPlayer) {
                try {
                    setPlayerState(PREPARED);

                    synchronized (DownloadService.this) {
                        if (position != 0) {
                            Log.i(TAG, "Restarting player from position " + position);
                            mediaPlayer.seekTo(position);
                        }
                        cachedPosition = position;

                        applyReplayGain(mediaPlayer, downloadFile);

                        if (start || autoPlayStart) {
                            mediaPlayer.start();
                            applyPlaybackParamsMain();
                            setPlayerState(STARTED);

                            // Disable autoPlayStart after done
                            autoPlayStart = false;
                        } else {
                            setPlayerState(PAUSED);
                            onSongProgress();
                        }

                        updateRemotePlaylist();
                    }

                    // Only call when starting, setPlayerState(PAUSED) already calls this
                    if (start) {
                        lifecycleSupport.serializeDownloadQueue();
                    }
                } catch (Exception x) {
                    handleError(x);
                }
            }
        });

        setupHandlers(downloadFile, isPartial, start);

        mediaPlayer.prepareAsync();
    } catch (Exception x) {
        handleError(x);
    }
}