Example usage for android.media MediaPlayer getDuration

List of usage examples for android.media MediaPlayer getDuration

Introduction

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

Prototype

public native int getDuration();

Source Link

Document

Gets the duration of the file.

Usage

From source file:com.polyvi.xface.extension.capture.MediaType.java

/**
 *  audio  video ./*from   ww w .  j ava  2  s. c o m*/
 *
 * @param fileAbsPath ?
 * @param obj ?
 * @param isVideo ? video
 * @return ? JSONObject
 * @throws JSONException
 */
private JSONObject getAudioVideoData(String fileAbsPath, JSONObject obj, boolean isVideo) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(fileAbsPath);
        player.prepare();
        obj.put(PROP_DURATION, player.getDuration() / XConstant.MILLISECONDS_PER_SECOND);
        if (isVideo) {
            obj.put(PROP_HEIGHT, player.getVideoHeight());
            obj.put(PROP_WIDTH, player.getVideoWidth());
        }
    } catch (IOException e) {
        XLog.e(CLASS_NAME, "Error: loading video file");
    }
    player.release();
    return obj;
}

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

public void fastForwardButtonClicked(View view) {
    MediaPlayer mediaPlayer = talkPlayerFragment.getMediaPlayer();
    int currentPosition = mediaPlayer.getCurrentPosition();
    int newPosition = Math.min(currentPosition + 15000, mediaPlayer.getDuration());
    mediaPlayer.seekTo(newPosition);/* ww w.ja v  a2 s .  co m*/
}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Get the Image specific attributes//  w w  w . ja v  a  2 s . c  om
 * 
 * @param filePath
 *            path to the file
 * @param obj
 *            represents the Media File Data
 * @param video
 *            if true get video attributes as well
 * @return a JSONObject that represents the Media File Data
 * @throws JSONException
 */
private JSONObject getAudioVideoMetadata(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put(DURATION_FIELD, player.getDuration());
        if (video) {
            obj.put(HEIGHT_FIELD, player.getVideoHeight());
            obj.put(WIDTH_FIELD, player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

    NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {//from   w ww .j  a va 2s .co m
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {/*from   ww  w .  j  a  va2s  . co m*/
        MediaPlayer tempPlayer = new MediaPlayer();
        tempPlayer.setDataSource(soundInfo.getAbsolutePath());
        tempPlayer.prepare();

        long milliseconds = tempPlayer.getDuration();
        long seconds = milliseconds / 1000;
        if (seconds == 0) {
            seconds = 1;
        }
        String timeDisplayed = DateUtils.formatElapsedTime(seconds);

        holder.timePlayedChronometer.setText(timeDisplayed);
        holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE);

        if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
            SoundBaseAdapter.setElapsedMilliSeconds(0);
        } else {
            SoundBaseAdapter.setElapsedMilliSeconds(
                    SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase());
        }

        if (soundInfo.isPlaying) {
            holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_stop);
            holder.playAndStopButton
                    .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_stop));

            if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
                startPlayingSound(holder.timePlayedChronometer, position, soundAdapter);
            } else if ((position == soundAdapter.getCurrentPlayingPosition())
                    && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) {
                stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
            } else {
                continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime());
            }
        } else {
            holder.playAndStopButton.setImageResource(hku.fyp14017.blencode.R.drawable.ic_media_play);
            holder.playAndStopButton
                    .setContentDescription(context.getString(hku.fyp14017.blencode.R.string.sound_play));
            stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
        }

        tempPlayer.reset();
        tempPlayer.release();
    } catch (IOException ioException) {
        Log.e(TAG, "Cannot get view.", ioException);
    }
}

From source file:org.catrobat.catroid.ui.controller.SoundController.java

private void handleSoundInfo(SoundViewHolder holder, SoundInfo soundInfo, SoundBaseAdapter soundAdapter,
        int position, Context context) {
    try {//from www .  j a  v a  2 s.  com
        MediaPlayer tempPlayer = new MediaPlayer();
        tempPlayer.setDataSource(soundInfo.getAbsolutePath());
        tempPlayer.prepare();

        long milliseconds = tempPlayer.getDuration();
        long seconds = milliseconds / 1000;
        if (seconds == 0) {
            seconds = 1;
        }
        String timeDisplayed = DateUtils.formatElapsedTime(seconds);

        holder.timePlayedChronometer.setText(timeDisplayed);
        holder.timePlayedChronometer.setVisibility(Chronometer.VISIBLE);

        if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
            SoundBaseAdapter.setElapsedMilliSeconds(0);
        } else {
            SoundBaseAdapter.setElapsedMilliSeconds(
                    SystemClock.elapsedRealtime() - SoundBaseAdapter.getCurrentPlayingBase());
        }

        if (soundInfo.isPlaying) {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_stop);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_stop));

            if (soundAdapter.getCurrentPlayingPosition() == Constants.NO_POSITION) {
                startPlayingSound(holder.timePlayedChronometer, position, soundAdapter);
            } else if ((position == soundAdapter.getCurrentPlayingPosition())
                    && (SoundBaseAdapter.getElapsedMilliSeconds() > (milliseconds - 1000))) {
                stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
            } else {
                continuePlayingSound(holder.timePlayedChronometer, SystemClock.elapsedRealtime());
            }
        } else {
            holder.playAndStopButton.setImageResource(R.drawable.ic_media_play);
            holder.playAndStopButton.setContentDescription(context.getString(R.string.sound_play));
            stopPlayingSound(soundInfo, holder.timePlayedChronometer, soundAdapter);
        }

        tempPlayer.reset();
        tempPlayer.release();
    } catch (IOException ioException) {
        Log.e(TAG, "Cannot get view.", ioException);
    }
}

From source file:com.cw.litenote.note.NoteUi.java

public NoteUi(AppCompatActivity activity, ViewPager viewPager, int position) {

    System.out.println("NoteUi / constructor");
    pager = viewPager;/*from w w  w  .ja  v a 2  s  .c  om*/
    act = activity;
    mPosition = position;

    DB_page db_page = new DB_page(act, TabsHost.getCurrentPageTableId());
    setNotesCnt(db_page.getNotesCount(true));
    String pictureUri = db_page.getNotePictureUri(position, true);
    String linkUri = db_page.getNoteLinkUri(position, true);

    String tagStr = "current" + position + "pictureView";
    ViewGroup pictureGroup = (ViewGroup) pager.findViewWithTag(tagStr);

    if ((pictureGroup != null)) {
        setPictureView_listeners(act, pager, pictureUri, linkUri, pictureGroup);

        TextView picView_footer = (TextView) (pictureGroup.findViewById(R.id.image_footer));

        Button picView_back_button = (Button) (pictureGroup.findViewById(R.id.image_view_back));
        Button picView_viewMode_button = (Button) (pictureGroup.findViewById(R.id.image_view_mode));

        TextView videoView_currPosition = (TextView) (pictureGroup.findViewById(R.id.video_current_pos));
        SeekBar videoView_seekBar = (SeekBar) (pictureGroup.findViewById(R.id.video_seek_bar));
        TextView videoView_fileLength = (TextView) (pictureGroup.findViewById(R.id.video_file_length));

        // show back button
        if (Note.isPictureMode())
            picView_back_button.setVisibility(View.VISIBLE);
        else
            picView_back_button.setVisibility(View.GONE);

        // Show picture title
        TextView picView_title;
        picView_title = (TextView) (pictureGroup.findViewById(R.id.image_title));
        String pictureName;
        if (!Util.isEmptyString(pictureUri))
            pictureName = Util.getDisplayNameByUriString(pictureUri, act);
        else if (Util.isYouTubeLink(linkUri))
            pictureName = linkUri;
        else
            pictureName = "";

        if (!Util.isEmptyString(pictureName)) {
            picView_title.setVisibility(View.VISIBLE);
            picView_title.setText(pictureName);
        } else
            picView_title.setVisibility(View.INVISIBLE);

        // show footer
        if (Note.isPictureMode()) {
            picView_footer.setVisibility(View.VISIBLE);
            picView_footer.setText((pager.getCurrentItem() + 1) + "/" + pager.getAdapter().getCount());
        } else
            picView_footer.setVisibility(View.GONE);

        // for video
        if (UtilVideo.hasVideoExtension(pictureUri, act)) {
            if (!UtilVideo.hasMediaControlWidget)
                NoteUi.updateVideoPlayButtonState(pager, getFocus_notePos());
            else
                show_picViewUI_previous_next(false, 0);
        }

        // set image view buttons (View Mode, Previous, Next) visibility
        if (Note.isPictureMode()) {
            picView_viewMode_button.setVisibility(View.VISIBLE);

            // show previous/next buttons for image, not for video
            if (UtilVideo.hasVideoExtension(pictureUri, act) && !UtilVideo.hasMediaControlWidget) // for video
            {
                System.out.println("NoteUi / constructor / for video");
                show_picViewUI_previous_next(true, position);
            } else if (UtilImage.hasImageExtension(pictureUri, act) && (UtilVideo.mVideoView == null))// for image
            {
                System.out.println("NoteUi / constructor / for image");
                show_picViewUI_previous_next(true, position);
            }
        } else {
            show_picViewUI_previous_next(false, 0);
            picView_viewMode_button.setVisibility(View.GONE);
        }

        // show seek bar for video only
        if (!UtilVideo.hasMediaControlWidget) {
            if (UtilVideo.hasVideoExtension(pictureUri, act)) {
                MediaPlayer mp = MediaPlayer.create(act, Uri.parse(pictureUri));

                if (mp != null) {
                    videoFileLength_inMilliSeconds = mp.getDuration();
                    mp.release();
                }

                primaryVideoSeekBarProgressUpdater(pager, position, UtilVideo.mPlayVideoPosition, pictureUri);
            } else {
                videoView_currPosition.setVisibility(View.GONE);
                videoView_seekBar.setVisibility(View.GONE);
                videoView_fileLength.setVisibility(View.GONE);
            }
        }

        showSeekBarProgress = true;
    }
}

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

public void playPauseButton() {
    if (status == PAUSE) {
        playPauseButton/*from w  ww.ja v  a 2  s  . c o 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.insthub.O2OMobile.Activity.C1_PublishOrderActivity.java

/**
 * ?//w  w  w . j a va 2s  . c o  m
 */
private void stopRecording() {
    if (mTimer != null) {
        mTimer.cancel(); //??
    }
    mTimer = null;
    if (mRecorder != null) {
        try {
            mRecorder.stop();
            mRecorder.reset();
            mRecorder.release();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
    mRecorder = null;

    MediaPlayer mp = MediaPlayer.create(this, Uri.parse(mFileName));
    if (null != mp) {
        int duration = mp.getDuration();//? ms
        if (duration > 3000) {
            mVoice.setVisibility(View.GONE);
            mVoicePlay.setVisibility(View.VISIBLE);
            mVoiceReset.setVisibility(View.VISIBLE);
        } else {
            ToastView toast = new ToastView(C1_PublishOrderActivity.this,
                    getString(R.string.record_time_too_short));
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            File file = new File(newFileName());
            if (file.exists()) {
                file.delete();
            }
        }
        mp.release();
    }
    mVoice.setKeepScreenOn(false);
}

From source file:com.nd.android.u.square.service.MusicPlaybackService.java

/**
 * Called when media player is done playing current song.
 *//*  w ww  .jav  a  2 s. c  o  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);
    }
}