Example usage for android.media MediaPlayer getCurrentPosition

List of usage examples for android.media MediaPlayer getCurrentPosition

Introduction

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

Prototype

public native int getCurrentPosition();

Source Link

Document

Gets the current playback position.

Usage

From source file:nuclei.media.playback.FallbackPlayback.java

/**
 * Called when MediaPlayer has completed a seek.
 *
 * @see OnSeekCompleteListener// www  .  j  av a2 s.c  om
 */
@Override
public void onSeekComplete(MediaPlayer mp) {
    mCurrentPosition = mp.getCurrentPosition();
    if (mState == PlaybackStateCompat.STATE_BUFFERING) {
        if (!mMediaPlayer.isPlaying())
            mMediaPlayer.start();
        mState = PlaybackStateCompat.STATE_PLAYING;
    }
    if (mCallback != null) {
        mCallback.onPlaybackStatusChanged(mState);
    }
}

From source file:com.baruckis.nanodegree.spotifystreamer.PlayerService.java

@Override
public void onCompletion(MediaPlayer mediaPlayer) {

    // Inform UI that track completed playing.
    if (!mIsError && mListener != null)
        mListener.onTrackComplete();/*from w w w .ja v  a  2s.  c o  m*/

    // Check if playback has reached the end of a track...
    if (!mIsError && mediaPlayer.getCurrentPosition() > 0) {
        mediaPlayer.reset();
        // ...if it reached than jump to the next one.
        playNext();
    }
}

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

public void playPauseButton() {
    if (status == PAUSE) {
        playPauseButton/*w ww.ja v  a 2s  . co m*/
                .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.nd.android.u.square.service.MusicPlaybackService.java

/**
 * Called when media player is done playing current song.
 *///from  ww  w . java2s .  co m
public void onCompletion(MediaPlayer player) {

    final int pos = player.getCurrentPosition();
    final int duration = player.getDuration();

    Log.d(TAG, "current position: " + pos + "/" + duration);
    Log.d(TAG, "Song " + mSongTitle + " buffered percent: " + mPlayingItem.bufferedPercent);

    if ((duration - pos) > 1000) {
        Log.d(TAG, "Song: " + mSongTitle + " uncompleted, stop it.");
        // onCompletion????????
        // ???durationpos??1000ms
        // 1000ms??
        mPlayingItem.lastPosition = pos;
        processStopRequest();

    } else {
        mPlayingItem.lastPosition = 0;
        Log.d(TAG, "Song: " + mSongTitle + " completed, try play next song.");
        // The media player finished playing the current song, so we go ahead and start the next.
        playNextSong(null);
    }
}

From source file:org.dharmaseed.android.PlayTalkActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play_talk);

    // Turn on action bar up/home button
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }//from  w w  w .ja  va2 s .co m

    // Get the ID of the talk to display
    Intent i = getIntent();
    talkID = (int) i.getLongExtra(NavigationActivity.TALK_DETAIL_EXTRA, 0);

    dbManager = DBManager.getInstance(this);

    // only hit the DB again if we know the talk is different than the one
    // we have saved.
    // for example, if the user selects a talk, exits, and re-opens it, no need
    // to hit the DB again, since we already have that talk saved
    if (talk == null || talk.getId() != talkID) {
        Cursor cursor = getCursor();
        if (cursor.moveToFirst()) {
            // convert DB result to an object
            talk = new Talk(cursor);
            talk.setId(talkID);
        } else {
            Log.e(LOG_TAG, "Could not look up talk, id=" + talkID);
            cursor.close();
            return;
        }
        cursor.close();
    } // else we already have the talk, just re-draw the page

    // Set the talk title
    TextView titleView = (TextView) findViewById(R.id.play_talk_talk_title);
    titleView.setText(talk.getTitle());

    // Set the teacher name
    TextView teacherView = (TextView) findViewById(R.id.play_talk_teacher);
    teacherView.setText(talk.getTeacherName());

    // Set the center name
    TextView centerView = (TextView) findViewById(R.id.play_talk_center);
    centerView.setText(talk.getCenterName());

    // Set the talk description
    TextView descriptionView = (TextView) findViewById(R.id.play_talk_talk_description);
    descriptionView.setText(talk.getDescription());

    // Set teacher photo
    String photoFilename = talk.getPhotoFileName();
    ImageView photoView = (ImageView) findViewById(R.id.play_talk_teacher_photo);
    Log.i(LOG_TAG, "photoFilename: " + photoFilename);
    try {
        FileInputStream photo = openFileInput(photoFilename);
        photoView.setImageBitmap(BitmapFactory.decodeStream(photo));
    } catch (FileNotFoundException e) {
        Drawable icon = ContextCompat.getDrawable(this, R.drawable.dharmaseed_icon);
        photoView.setImageDrawable(icon);
    }

    // set the image of the download button based on whether the talk is
    // downloaded or not
    toggleDownloadImage();

    // Set date
    TextView dateView = (TextView) findViewById(R.id.play_talk_date);
    String recDate = talk.getDate();
    SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        dateView.setText(DateFormat.getDateInstance().format(parser.parse(recDate)));
    } catch (ParseException e) {
        dateView.setText("");
        Log.w(LOG_TAG, "Could not parse talk date for talk ID " + talkID);
    }

    // Get/create a persistent fragment to manage the MediaPlayer instance
    FragmentManager fm = getSupportFragmentManager();
    talkPlayerFragment = (TalkPlayerFragment) fm.findFragmentByTag("talkPlayerFragment");
    if (talkPlayerFragment == null) {
        // add the fragment
        talkPlayerFragment = new TalkPlayerFragment();
        fm.beginTransaction().add(talkPlayerFragment, "talkPlayerFragment").commit();
    } else if (talkPlayerFragment.getMediaPlayer().isPlaying()) {
        setPPButton("ic_media_pause");
    }

    // Set the talk duration
    final TextView durationView = (TextView) findViewById(R.id.play_talk_talk_duration);
    double duration = talk.getDurationInMinutes();
    String durationStr = DateUtils.formatElapsedTime((long) (duration * 60));
    durationView.setText(durationStr);

    // Start a handler to periodically update the seek bar and talk time
    final SeekBar seekBar = (SeekBar) findViewById(R.id.play_talk_seek_bar);
    seekBar.setMax((int) (duration * 60 * 1000));
    userDraggingSeekBar = false;
    userSeekBarPosition = 0;
    seekBar.setOnSeekBarChangeListener(this);
    final Handler handler = new Handler();
    final MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    handler.post(new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, 1000);
            if (talkPlayerFragment.getMediaPrepared() && !userDraggingSeekBar) {
                try {
                    int pos = mediaPlayer.getCurrentPosition();
                    int mpDuration = mediaPlayer.getDuration();
                    seekBar.setMax(mpDuration);
                    seekBar.setProgress(pos);
                    String posStr = DateUtils.formatElapsedTime(pos / 1000);
                    String mpDurStr = DateUtils.formatElapsedTime(mpDuration / 1000);
                    durationView.setText(posStr + "/" + mpDurStr);
                } catch (IllegalStateException e) {
                }
            }
        }
    });
}

From source file:com.quran.labs.androidquran.service.AudioService.java

@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
    Log.d(TAG, "seek complete! " + mediaPlayer.getCurrentPosition() + " vs " + mPlayer.getCurrentPosition());
    mPlayer.start();/*from w ww. java  2  s . c om*/
    mHandler.sendEmptyMessageDelayed(MSG_UPDATE_AUDIO_POS, 200);
}

From source file:net.sourceforge.kalimbaradio.androidapp.service.DownloadServiceImpl.java

private synchronized void doPlay(final DownloadFile downloadFile, int position, boolean start) {
    try {/*from w  ww .jav  a 2s  .c  o  m*/
        final File file = downloadFile.isCompleteFileAvailable() ? downloadFile.getCompleteFile()
                : downloadFile.getPartialFile();
        downloadFile.updateModificationDate();
        mediaPlayer.setOnCompletionListener(null);
        mediaPlayer.reset();
        setPlayerState(IDLE);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setDataSource(file.getPath());
        setPlayerState(PREPARING);
        mediaPlayer.prepare();
        setPlayerState(PREPARED);

        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(60000);

                setPlayerState(COMPLETED);

                // If COMPLETED and not playing partial file, we are *really" finished
                // with the song and can move on to the next.
                if (!file.equals(downloadFile.getPartialFile())) {
                    onSongCompleted();
                    return;
                }

                // If file is not completely downloaded, restart the playback from the current position.
                int pos = mediaPlayer.getCurrentPosition();
                synchronized (DownloadServiceImpl.this) {

                    // Work-around for apparent bug on certain phones: If close (less than ten seconds) to the end
                    // of the song, skip to the next rather than restarting it.
                    Integer duration = downloadFile.getSong().getDuration() == null ? null
                            : downloadFile.getSong().getDuration() * 1000;
                    if (duration != null) {
                        if (Math.abs(duration - pos) < 10000) {
                            LOG.info("Skipping restart from " + pos + " of " + duration);
                            onSongCompleted();
                            return;
                        }
                    }

                    LOG.info("Requesting restart from " + pos + " of " + duration);
                    reset();
                    bufferTask = new BufferTask(downloadFile, pos);
                    bufferTask.start();
                }
            }
        });

        if (position != 0) {
            LOG.info("Restarting player from position " + position);
            mediaPlayer.seekTo(position);
        }

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

    } catch (Exception x) {
        handleError(x);
    }
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void setVideo(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        @Override/*from w w  w. ja va2  s . c  o m*/
        public void run() {
            setOnClickView(tag, getString(R.string.gallery_tap_to_play), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!settings.useInternalVideoPlayer()) {
                        openExternal();
                    } else {
                        recycleTag(tag, false);
                        tag.thumbnailView.setVisibility(View.GONE);
                        View videoContainer = inflater.inflate(R.layout.gallery_videoplayer, tag.layout);
                        final VideoView videoView = (VideoView) videoContainer
                                .findViewById(R.id.gallery_video_view);
                        final TextView durationView = (TextView) videoContainer
                                .findViewById(R.id.gallery_video_duration);

                        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(final MediaPlayer mp) {
                                mp.setLooping(true);

                                durationView.setText("00:00 / " + formatMediaPlayerTime(mp.getDuration()));

                                tag.timer = new Timer();
                                tag.timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    durationView.setText(
                                                            formatMediaPlayerTime(mp.getCurrentPosition())
                                                                    + " / "
                                                                    + formatMediaPlayerTime(mp.getDuration()));
                                                } catch (Exception e) {
                                                    Logger.e(TAG, e);
                                                    tag.timer.cancel();
                                                }
                                            }
                                        });
                                    }
                                }, 1000, 1000);

                                videoView.start();
                            }
                        });
                        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                Logger.e(TAG, "(Video) Error code: " + what);
                                if (tag.timer != null)
                                    tag.timer.cancel();
                                showError(tag, getString(R.string.gallery_error_play));
                                return true;
                            }
                        });

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                            CompatibilityImpl.setVideoViewZOrderOnTop(videoView);
                        }
                        videoView.setVideoPath(file.getAbsolutePath());
                    }
                }

            });
        }
    });
}

From source file:com.nttec.everychan.ui.gallery.GalleryActivity.java

private void setAudio(final GalleryItemViewTag tag, final File file) {
    runOnUiThread(new Runnable() {
        @Override//  ww  w .j  a  va  2 s.  c o m
        public void run() {
            setOnClickView(tag, getString(R.string.gallery_tap_to_play), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!settings.useInternalAudioPlayer()) {
                        openExternal();
                    } else {
                        recycleTag(tag, false);
                        final TextView durationView = new TextView(GalleryActivity.this);
                        durationView.setGravity(Gravity.CENTER);
                        tag.layout.setVisibility(View.VISIBLE);
                        tag.layout.addView(durationView);
                        tag.audioPlayer = new MediaPlayer();
                        tag.audioPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(final MediaPlayer mp) {
                                mp.setLooping(true);

                                durationView.setText(
                                        getSpannedText("00:00 / " + formatMediaPlayerTime(mp.getDuration())));

                                tag.timer = new Timer();
                                tag.timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                try {
                                                    durationView.setText(getSpannedText(
                                                            formatMediaPlayerTime(mp.getCurrentPosition())
                                                                    + " / "
                                                                    + formatMediaPlayerTime(mp.getDuration())));
                                                } catch (Exception e) {
                                                    Logger.e(TAG, e);
                                                    tag.timer.cancel();
                                                }
                                            }
                                        });
                                    }
                                }, 1000, 1000);

                                mp.start();
                            }
                        });
                        tag.audioPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                Logger.e(TAG, "(Audio) Error code: " + what);
                                if (tag.timer != null)
                                    tag.timer.cancel();
                                showError(tag, getString(R.string.gallery_error_play));
                                return true;
                            }
                        });
                        try {
                            tag.audioPlayer.setDataSource(file.getAbsolutePath());
                            tag.audioPlayer.prepareAsync();
                        } catch (Exception e) {
                            Logger.e(TAG, "audio player error", e);
                            if (tag.timer != null)
                                tag.timer.cancel();
                            showError(tag, getString(R.string.gallery_error_play));
                        }
                    }
                }
            });
        }
    });
}