Example usage for android.media MediaMetadataRetriever METADATA_KEY_DURATION

List of usage examples for android.media MediaMetadataRetriever METADATA_KEY_DURATION

Introduction

In this page you can find the example usage for android.media MediaMetadataRetriever METADATA_KEY_DURATION.

Prototype

int METADATA_KEY_DURATION

To view the source code for android.media MediaMetadataRetriever METADATA_KEY_DURATION.

Click Source Link

Document

The metadata key to retrieve the playback duration of the data source.

Usage

From source file:Main.java

public static long getVideoDurationInMillis(String videoFile) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(videoFile);/*from   w  ww .  jav  a2  s .co m*/
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    long timeInmillisec = Long.parseLong(time);
    retriever.release();
    return timeInmillisec;
}

From source file:Main.java

public static long getVideoAssetDurationMilliSec(Context context, Uri uri) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(context, uri);
    String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
    return Long.parseLong(time);
}

From source file:jp.seikeidenron.androidtv.common.Utils.java

public static long getDuration(String videoUrl) {
    MediaMetadataRetriever mmr = new MediaMetadataRetriever();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mmr.setDataSource(videoUrl, new HashMap<String, String>());
    } else {/*from w  ww  . ja  v a 2  s . c  o  m*/
        mmr.setDataSource(videoUrl);
    }
    return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
}

From source file:com.sebible.cordova.videosnapshot.VideoSnapshot.java

/**
 * Take snapshots of a video file/*from  w ww . j a v a2 s  .  c  o  m*/
 *
 * @param source path of the file
 * @param count of snapshots that are gonna be taken
 */
private void snapshot(final JSONObject options) {
    final CallbackContext context = this.callbackContext;
    this.cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            try {
                int count = options.optInt("count", 1);
                int countPerMinute = options.optInt("countPerMinute", 0);
                int quality = options.optInt("quality", 90);
                String source = options.optString("source", "");
                Boolean timestamp = options.optBoolean("timeStamp", true);
                String prefix = options.optString("prefix", "");
                int textSize = options.optInt("textSize", 48);

                if (source.isEmpty()) {
                    throw new Exception("No source provided");
                }

                JSONObject obj = new JSONObject();
                obj.put("result", false);
                JSONArray results = new JSONArray();

                Log.i("snapshot", "Got source: " + source);
                Uri p = Uri.parse(source);
                String filename = p.getLastPathSegment();

                FileInputStream in = new FileInputStream(new File(p.getPath()));
                retriever.setDataSource(in.getFD());
                String tmp = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long duration = Long.parseLong(tmp);
                if (countPerMinute > 0) {
                    count = (int) (countPerMinute * duration / (60 * 1000));
                }
                if (count < 1) {
                    count = 1;
                }
                long delta = duration / (count + 1); // Start at duration * 1 and ends at duration * count
                if (delta < 1000) { // min 1s
                    delta = 1000;
                }

                Log.i("snapshot", "duration:" + duration + " delta:" + delta);

                File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                for (int i = 1; delta * i < duration && i <= count; i++) {
                    String filename2 = filename.replace('.', '_') + "-snapshot" + i + ".jpg";
                    File dest = new File(storage, filename2);
                    if (!storage.exists() && !storage.mkdirs()) {
                        throw new Exception("Unable to access storage:" + storage.getPath());
                    }
                    FileOutputStream out = new FileOutputStream(dest);
                    Bitmap bm = retriever.getFrameAtTime(i * delta * 1000);
                    if (timestamp) {
                        drawTimestamp(bm, prefix, delta * i, textSize);
                    }
                    bm.compress(Bitmap.CompressFormat.JPEG, quality, out);
                    out.flush();
                    out.close();
                    results.put(dest.getAbsolutePath());
                }

                obj.put("result", true);
                obj.put("snapshots", results);
                context.success(obj);
            } catch (Exception ex) {
                ex.printStackTrace();
                Log.e("snapshot", "Exception:", ex);
                fail("Exception: " + ex.toString());
            } finally {
                try {
                    retriever.release();
                } catch (RuntimeException ex) {
                }
            }
        }
    });
}

From source file:org.gateshipone.odyssey.utils.FileExplorerHelper.java

/**
 * create a TrackModel for the given File
 * if no entry in the mediadb is found a dummy TrackModel will be created
 *//*from w  ww .ja va 2  s .  c  o  m*/
public TrackModel getTrackModelForFile(Context context, FileModel file) {
    TrackModel track = null;

    String urlString = file.getURLString();

    if (mTrackHash.isEmpty()) {
        // lookup the current file in the media db
        String whereVal[] = { urlString };

        String where = MediaStore.Audio.Media.DATA + "=?";

        Cursor cursor = PermissionHelper.query(context, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MusicLibraryHelper.projectionTracks, where, whereVal, MediaStore.Audio.Media.TRACK);

        if (cursor != null) {
            if (cursor.moveToFirst()) {
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
                int no = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
                String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
                String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
                String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String albumKey = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_KEY));
                long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));

                track = new TrackModel(title, artist, album, albumKey, duration, no, url, id);
            }

            cursor.close();
        }
    } else {
        // use pre built hash to lookup the file
        track = mTrackHash.get(urlString);
    }

    if (track == null) {
        // no entry in the media db was found so create a custom track
        try {
            // try to read the file metadata

            MediaMetadataRetriever retriever = new MediaMetadataRetriever();

            retriever.setDataSource(context, Uri.parse(FormatHelper.encodeFileURI(urlString)));

            String title = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);

            if (title == null) {
                title = file.getName();
            }

            String durationString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

            long duration = 0;

            if (durationString != null) {
                try {
                    duration = Long.valueOf(durationString);
                } catch (NumberFormatException e) {
                    duration = 0;
                }
            }

            String noString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_CD_TRACK_NUMBER);

            int no = -1;

            if (noString != null) {
                try {
                    if (noString.contains("/")) {
                        // if string has the format (trackNumber / numberOfTracks)
                        String[] components = noString.split("/");
                        if (components.length > 0) {
                            no = Integer.valueOf(components[0]);
                        }
                    } else {
                        no = Integer.valueOf(noString);
                    }
                } catch (NumberFormatException e) {
                    no = -1;
                }
            }

            String artist = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            String album = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);

            String albumKey = "" + ((artist == null ? "" : artist) + (album == null ? "" : album)).hashCode();

            track = new TrackModel(title, artist, album, albumKey, duration, no, urlString, -1);
        } catch (Exception e) {
            String albumKey = "" + file.getName().hashCode();
            track = new TrackModel(file.getName(), "", "", albumKey, 0, -1, urlString, -1);
        }
    }

    return track;
}

From source file:com.univpm.s1055802.faceplusplustester.Detect.AcquireVideo.java

/**
 * Estrae un frame per ogni secondo del video e li salva sul dispositivo
 * @param uri uri della cartella dove salvare i frames
 *//*  ww w . ja v  a2  s  .c o m*/
private void captureFrames(Uri uri) {
    String filePath = FileUtils.getPath(getApplicationContext(), uri);
    File video = new File(filePath);
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(filePath);
        double duration = Double
                .parseDouble(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
        Log.v("duration", String.valueOf(duration));

        int timeSkip = 1000000;
        for (int i = 0; i < duration * 1000; i = i + timeSkip) {
            File img = null;
            try {
                img = new File(framesDir, "Frame_" + String.valueOf(i / timeSkip) + ".jpg");
                OutputStream fOut = null;
                fOut = new FileOutputStream(img);
                Bitmap imgBmp = retriever.getFrameAtTime(i, MediaMetadataRetriever.OPTION_NEXT_SYNC);
                imgBmp.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }

}

From source file:com.achep.acdisplay.services.media.MediaController2KitKat.java

/**
 * Updates {@link #mMetadata metadata} from given remote metadata class.
 * This also updates play state.//ww  w .j  a v  a2  s .  com
 *
 * @param data Object of metadata to update from, or {@code null} to clear local metadata.
 * @see #clearMetadata()
 */
private void updateMetadata(@Nullable RemoteController.MetadataEditor data) {
    if (data == null) {
        if (mMetadata.isEmpty())
            return;
        mMetadata.clear();
    } else {
        mMetadata.title = data.getString(MediaMetadataRetriever.METADATA_KEY_TITLE, null);
        mMetadata.artist = data.getString(MediaMetadataRetriever.METADATA_KEY_ARTIST, null);
        mMetadata.album = data.getString(MediaMetadataRetriever.METADATA_KEY_ALBUM, null);
        mMetadata.duration = data.getLong(MediaMetadataRetriever.METADATA_KEY_DURATION, -1);
        mMetadata.bitmap = data.getBitmap(MediaMetadataEditor.BITMAP_KEY_ARTWORK, null);
        mMetadata.generateSubtitle();
    }

    notifyOnMetadataChanged();
}

From source file:com.psu.capstonew17.pdxaslapp.CreateCardActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    switch (requestCode) {
    //We be getting a video! yay!
    case GET_VIDEO:
        if (resultCode == RESULT_OK) {
            videoUri = intent.getData();

            if (videoUri != null) {
                //Verify length of video is greater than two seconds
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(this, videoUri);
                int endTime = Integer
                        .parseInt(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
                if (endTime < MIN_VIDEO_LENGTH || endTime > MAX_VIDEO_LENGTH) {
                    Toast.makeText(this, R.string.bad_video_length, Toast.LENGTH_SHORT).show();
                } else {
                    //if they had previously imported a video but changed their minds and imported
                    //a different video then we need to stop payback of the old one and hide some
                    //views while the new one imports.
                    stopVideo();/* w ww . ja  v  a  2s .c  o  m*/

                    //lets get the import options the user wants
                    VideoManager.ImportOptions imo = new VideoManager.ImportOptions();
                    imo.startTime = 0;
                    imo.endTime = endTime;
                    imo.quality = 20;
                    imo.cropRegion = null;

                    //block with a spin wheel while the video is imported
                    progressDialog.show();

                    //now we can import the new video.
                    video = null;
                    VideoManager vm = ExternalVideoManager.getInstance(this);
                    vm.importVideo(this, videoUri, imo, new VideoManager.VideoImportListener() {
                        //this is behaving weirdly with a horizontal progress bar, so for now I'm
                        //ignoring it in favor of a spin wheel
                        @Override
                        public void onProgressUpdate(int current, int max) {
                        }

                        //this is called when the import has completed
                        //we get the video, display it and the submit button,
                        //and then hide the progress dialog.
                        @Override
                        public void onComplete(Video vid) {
                            video = vid;
                            startVideo();
                            progressDialog.dismiss();
                            Toast.makeText(CreateCardActivity.this, R.string.video_delete_safe,
                                    Toast.LENGTH_LONG).show();
                        }

                        //if importing fails.
                        @Override
                        public void onFailed(Throwable err) {
                            Toast.makeText(CreateCardActivity.this, R.string.import_video_error,
                                    Toast.LENGTH_SHORT).show();
                            progressDialog.dismiss();
                        }
                    });
                }
            }
        }
        break;
    }
}

From source file:life.knowledge4.videotrimmer.K4LVideoTrimmer.java

public void onSaveClicked() {
    if (mOnTrimVideoListener != null && !mOnTrimVideoListener.shouldTrim()) {
        onTrimFinished();//from  www.j  ava  2  s  . c  om
        return;
    }

    if (mStartPosition <= 0 && mEndPosition >= mDuration) {
        if (mOnTrimVideoListener != null)
            mOnTrimVideoListener.getResult(mSrc);
    } else {
        mPlayView.setVisibility(View.VISIBLE);
        mVideoView.pause();

        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(getContext(), mSrc);
        long METADATA_KEY_DURATION = Long.parseLong(
                mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));

        final File file = new File(mSrc.getPath());

        if (mTimeVideo < MIN_TIME_FRAME) {

            if ((METADATA_KEY_DURATION - mEndPosition) > (MIN_TIME_FRAME - mTimeVideo)) {
                mEndPosition += (MIN_TIME_FRAME - mTimeVideo);
            } else if (mStartPosition > (MIN_TIME_FRAME - mTimeVideo)) {
                mStartPosition -= (MIN_TIME_FRAME - mTimeVideo);
            }
        }

        Log.d(TAG, "onSaveClicked: mStartPosition: " + stringForTime(mStartPosition) + " #### mEndPosition: "
                + stringForTime(mEndPosition));

        final File root = new File(Environment.getExternalStorageDirectory() + File.separator
                + "k4lVideoTrimmer" + File.separator);
        root.mkdirs();
        final String fname = "t_" + mSrc.getPath().substring(mSrc.getPath().lastIndexOf("/") + 1);
        final File sdImageMainDirectory = new File(root, fname);
        final Uri outputFileUri = Uri.fromFile(sdImageMainDirectory);

        final String outPutPath = getRealPathFromUri(outputFileUri);

        FFmpeg ffmpeg = FFmpeg.getInstance(getContext());
        String[] command = { "-y", "-i", file.getPath(), "-ss", stringForTime(mStartPosition), "-to",
                stringForTime(mEndPosition), "-c", "copy", outPutPath };//{"-y", "-ss", "00:00:03", "-i", file.getPath(), "-t", "00:00:08", "-async", "1", outPutPath};  //-i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 cut.mp4
        try {
            ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
                @Override
                public void onSuccess(String message) {
                    super.onSuccess(message);
                    Log.d(TAG, "onSuccess: " + message);
                }

                @Override
                public void onProgress(String message) {
                    super.onProgress(message);
                    Log.d(TAG, "onProgress: " + message);
                }

                @Override
                public void onFailure(String message) {
                    super.onFailure(message);
                    loading.setVisibility(GONE);
                    Log.d(TAG, "onFailure: " + message);
                }

                @Override
                public void onStart() {
                    super.onStart();
                    Log.d(TAG, "onStart: ");
                }

                @Override
                public void onFinish() {
                    super.onFinish();
                    loading.setVisibility(GONE);
                    mOnTrimVideoListener.getResult(outputFileUri);
                    Log.d(TAG, "onFinish: ");
                }
            });
        } catch (FFmpegCommandAlreadyRunningException e) {

        }

        //notify that video trimming started
        if (mOnTrimVideoListener != null)
            mOnTrimVideoListener.onTrimStarted();
        //<<<<<<< HEAD
        //=======
        //
        //            BackgroundExecutor.execute(
        //                    new BackgroundExecutor.Task("", 0L, "") {
        //                        @Override
        //                        public void execute() {
        //                            try {
        //                                TrimVideoUtils.startTrim(file, new File(getDestinationPath(), UUID.randomUUID().toString()), mStartPosition, mEndPosition, mOnTrimVideoListener);
        //                            } catch (final Throwable e) {
        //                                Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
        //                            }
        //                        }
        //                    }
        //            );
        //>>>>>>> e9b3dcbb38ccfa62307fc2fb020bcb4d35933afa
    }
}

From source file:at.ac.tuwien.detlef.fragments.PlayerFragment.java

private void setNotPlayingSeekBarAndTime(Episode ep) {
    if (service == null) {
        return;//from  ww  w  .  j a va  2s  . co m
    }
    if (trackingTouch) {
        return;
    }
    try {
        if (service.episodeFileOK(ep)) {
            MediaMetadataRetriever metaData = new MediaMetadataRetriever();
            metaData.setDataSource(ep.getFilePath());
            String durationString = metaData.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            int duration = Integer.parseInt(durationString);
            int playingPosition = ep.getPlayPosition();
            int pos = 0;
            if (((playingPosition) > 0) && (playingPosition < duration)) {
                pos = playingPosition;
            }
            String minutesSecondsRemaining = getRemainingTime(duration, pos);
            String minutesSecondsAlreadyPlayed = getAlreadyPlayed(pos);
            remainingTime.setText("-" + minutesSecondsRemaining);
            alreadyPlayed.setText(minutesSecondsAlreadyPlayed);
            seekBar.setMax(duration);
            seekBar.setProgress(pos);
            seekBar.setSecondaryProgress(0);
        } else if ((service.getNextEpisode() == ep) && service.hasRunningEpisode()) {
            seekBar.setMax(service.getDuration());
            seekBar.setProgress(service.getCurrentPosition());
            alreadyPlayed.setText(getAlreadyPlayed(service.getCurrentPosition()));
            remainingTime.setText("-" + getRemainingTime(service.getDuration(), service.getCurrentPosition()));
        }
    } catch (Exception ex) {
        Log.d(getClass().getName(), "Error while retrieving duration of episode: " + ex.getMessage());
    }
}