Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import android.content.Context;

import android.database.Cursor;

import android.media.MediaPlayer;
import android.net.Uri;

import android.provider.MediaStore;

public class Main {
    /**
     * Get video's duration without {@link ContentProvider}. Because not know
     * {@link Uri} of video.
     *
     * @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;
    }

    /**
     * Get video's duration from {@link ContentProvider}
     *
     * @param context
     * @param uri     must has {@link Uri#getScheme()} equals
     *                {@link ContentResolver#SCHEME_CONTENT}
     * @return Duration of video, in milliseconds.
     */
    public static long getDuration(Context context, Uri uri) {
        long duration = 0L;
        Cursor cursor = MediaStore.Video.query(context.getContentResolver(), uri,
                new String[] { MediaStore.Video.VideoColumns.DURATION });
        if (cursor != null) {
            cursor.moveToFirst();
            duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.VideoColumns.DURATION));
            cursor.close();
        }
        return duration;
    }
}