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:Main.java

public static int m6967a(Context context, String str) {
    MediaPlayer create = MediaPlayer.create(context, Uri.parse(str));
    if (create == null) {
        return 0;
    }//from   w w w.  j a  v a  2 s. c o  m
    int duration = create.getDuration() / 1000;
    create.reset();
    create.release();
    return duration;
}

From source file:Main.java

/**
 * Get video's duration without {@link ContentProvider}. Because not know
 * {@link Uri} of video.//from  w  ww.  j  av a 2  s .  c o m
 *
 * @param context
 * @param path    Path of video file.
 * @return Duration of video, in milliseconds. Return 0 if path is null.
 */
public static long getDuration(Context context, String path) {
    MediaPlayer mMediaPlayer = null;
    long duration = 0;
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource(context, Uri.parse(path));
        mMediaPlayer.prepare();
        duration = mMediaPlayer.getDuration();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    return duration;
}

From source file:es.deustotech.piramide.utils.tts.TextToSpeechWeb.java

private static synchronized void speech(final Context context, final String text, final String language) {
    executor.submit(new Runnable() {
        @Override//w ww. j av  a  2  s  .co m
        public void run() {
            try {
                final String encodedUrl = Constants.URL + language + "&q="
                        + URLEncoder.encode(text, Encoding.UTF_8.name());
                final DefaultHttpClient client = new DefaultHttpClient();
                HttpParams params = new BasicHttpParams();
                params.setParameter("http.protocol.content-charset", "UTF-8");
                client.setParams(params);
                final FileOutputStream fos = context.openFileOutput(Constants.MP3_FILE,
                        Context.MODE_WORLD_READABLE);
                try {
                    try {
                        final HttpResponse response = client.execute(new HttpGet(encodedUrl));
                        downloadFile(response, fos);
                    } finally {
                        fos.close();
                    }
                    final String filePath = context.getFilesDir().getAbsolutePath() + "/" + Constants.MP3_FILE;
                    final MediaPlayer player = MediaPlayer.create(context.getApplicationContext(),
                            Uri.fromFile(new File(filePath)));
                    player.start();
                    Thread.sleep(player.getDuration());
                    while (player.isPlaying()) {
                        Thread.sleep(100);
                    }
                    player.stop();

                } finally {
                    context.deleteFile(Constants.MP3_FILE);
                }
            } catch (InterruptedException ie) {
                // ok
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

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

public static void initAudioProgress(AppCompatActivity act, String audioUriInDB, ViewPager _pager) {
    SeekBar seekBar = (SeekBar) act.findViewById(R.id.pager_img_audio_seek_bar);
    ImageView mPager_audio_play_button = (ImageView) act.findViewById(R.id.pager_btn_audio_play);

    // set audio block listeners
    setAudioBlockListener(act, audioUriInDB, _pager);

    mProgress = 0;//  ww  w  .  j a  v a  2s. co  m

    mAudioUriInDB = audioUriInDB;
    showAudioName(act);

    TextView audioTitle = (TextView) act.findViewById(R.id.pager_audio_title);
    audioTitle.setSelected(false);
    mPager_audio_play_button.setImageResource(R.drawable.ic_media_play);
    audioTitle.setTextColor(ColorSet.getPauseColor(act));
    audioTitle.setSelected(false);

    // current position
    int curHour = Math.round((float) (mProgress / 1000 / 60 / 60));
    int curMin = Math.round((float) ((mProgress - curHour * 60 * 60 * 1000) / 1000 / 60));
    int curSec = Math.round((float) ((mProgress - curHour * 60 * 60 * 1000 - curMin * 60 * 1000) / 1000));
    String curr_pos_str = String.format(Locale.ENGLISH, "%2d", curHour) + ":"
            + String.format(Locale.ENGLISH, "%02d", curMin) + ":"
            + String.format(Locale.ENGLISH, "%02d", curSec);

    TextView audio_curr_pos = (TextView) act.findViewById(R.id.pager_audio_current_pos);
    audio_curr_pos.setText(curr_pos_str);
    audio_curr_pos.setTextColor(ColorSet.color_white);

    // audio seek bar
    seekBar.setProgress(mProgress); // This math construction give a percentage of "was playing"/"song length"
    seekBar.setMax(99); // It means 100% .0-99
    seekBar.setVisibility(View.VISIBLE);

    // get audio file length
    try {
        if (Util.isUriExisted(mAudioUriInDB, act)) {
            MediaPlayer mp = MediaPlayer.create(act, Uri.parse(mAudioUriInDB));
            mediaFileLength = mp.getDuration();
            mp.release();
        }
    } catch (Exception e) {
        System.out.println("AudioUi_note / _initAudioProgress / exception");
    }
    // set audio file length
    int fileHour = Math.round((float) (mediaFileLength / 1000 / 60 / 60));
    int fileMin = Math.round((float) ((mediaFileLength - fileHour * 60 * 60 * 1000) / 1000 / 60));
    int fileSec = Math
            .round((float) ((mediaFileLength - fileHour * 60 * 60 * 1000 - fileMin * 1000 * 60) / 1000));

    String strHour = String.format(Locale.ENGLISH, "%2d", fileHour);
    String strMinute = String.format(Locale.ENGLISH, "%02d", fileMin);
    String strSecond = String.format(Locale.ENGLISH, "%02d", fileSec);
    String strLength = strHour + ":" + strMinute + ":" + strSecond;

    TextView audio_length = (TextView) act.findViewById(R.id.pager_audio_file_length);
    audio_length.setText(strLength);
    audio_length.setTextColor(ColorSet.color_white);
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static long getDurationTimeFromFile(String filePath) {
    if (StringUtility.isEmpty(filePath)) {
        AIOLog.e(MyCallRecorderConstant.TAG, "filePath is null");
        return 0;
    }//from www . j  a v a2  s.co  m
    File file = new File(filePath);
    if (file == null || !file.exists()) {
        Log.d("KieuThang", "file it not exitsted!");
    }
    MediaPlayer mediaPlayer = new MediaPlayer();
    long duration = 0L;
    try {
        mediaPlayer.setDataSource(filePath);
        mediaPlayer.prepare();
        duration = mediaPlayer.getDuration();
        mediaPlayer.reset();
        mediaPlayer.release();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //the valid time we offer to save at least more than 1s
    if (duration > 1000) {
        AIOLog.d(MyCallRecorderConstant.TAG, "InValid time:" + duration);
        return duration;
    }
    AIOLog.d(MyCallRecorderConstant.TAG, "Valid time:" + duration);
    return 0;
}

From source file:com.xlythe.engine.theme.Theme.java

public static long getDurationOfSound(Context context, Theme.Res res) {
    int millis = 0;
    MediaPlayer mp = new MediaPlayer();
    try {/* www.  j  a v a 2 s  .c  om*/
        AssetFileDescriptor afd;
        int id = getId(context, res.getType(), res.getName());
        if (id == 0) {
            id = context.getResources().getIdentifier(res.getName(), res.getType(), context.getPackageName());
            afd = context.getResources().openRawResourceFd(id);
        }

        afd = getThemeContext(context).getResources().openRawResourceFd(id);
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        afd.close();
        mp.prepare();
        millis = mp.getDuration();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        mp.release();
        mp = null;
    }

    return millis;
}

From source file:com.shahenlibrary.VideoPlayer.VideoPlayerView.java

@Override
public void onPrepared(MediaPlayer mp) {
    videoEndAt = mp.getDuration();
    setScalableType(ScalableType.FIT_XY);
    invalidate();

    applyProps();
}

From source file:com.phonegap.Capture.java

/**
 * Get the Image specific attributes//from   w  ww.j a  va  2 s  .  c  o  m
 * 
 * @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 getAudioVideoData(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put("duration", player.getDuration());
        if (video) {
            obj.put("height", player.getVideoHeight());
            obj.put("width", player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:org.apache.cordova.Capture.java

/**
 * Get the Image specific attributes/*from www  .j  ava  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 getAudioVideoData(String filePath, JSONObject obj, boolean video) throws JSONException {
    MediaPlayer player = new MediaPlayer();
    try {
        player.setDataSource(filePath);
        player.prepare();
        obj.put("duration", player.getDuration() / 1000);
        if (video) {
            obj.put("height", player.getVideoHeight());
            obj.put("width", player.getVideoWidth());
        }
    } catch (IOException e) {
        Log.d(LOG_TAG, "Error: loading video file");
    }
    return obj;
}

From source file:ui.GalleryFileActivity.java

private void doPlay() {
    recordBtn.setText("?");
    if (!TextUtils.isEmpty(voicePath)) {
        try {//from w  ww. j  a  v a 2  s  .c o  m
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
                mHandler.sendEmptyMessage(2);
                return;
            }
            if (mMediaPlayer == null) {
                mMediaPlayer = new MediaPlayer();
            }
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(voicePath);
            mMediaPlayer.prepare();

        } catch (Exception e) {
            e.printStackTrace();
        }
        mMediaPlayer.start();
        mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {

            @Override
            public void onPrepared(MediaPlayer mp) {
                int time = mp.getDuration() / 1000;
                voice_file.setText(Util.formatLongToTimeStr(time));
                mHandler.post(updateThread);
            }
        });
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.stop();
                mp.reset();
                mHandler.sendEmptyMessage(2);

            }
        });

        mMediaPlayer.setOnErrorListener(new OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int arg1, int arg2) {
                mp.stop();
                mp.reset();
                mHandler.sendEmptyMessage(2);
                return false;
            }
        });
    }

}