Example usage for android.media MediaMetadataRetriever extractMetadata

List of usage examples for android.media MediaMetadataRetriever extractMetadata

Introduction

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

Prototype

public native String extractMetadata(int keyCode);

Source Link

Document

Call this method after setDataSource().

Usage

From source file:Main.java

public static String getMetadataInfo(MediaMetadataRetriever retriever, int tag) {
    String value;//from   ww w.  ja v  a  2  s.c om
    if (tag != -1) {
        value = retriever.extractMetadata(tag);
        Log.d(LOG_TAG, "Return metadata with tag : " + tag + " value: " + value);
        return value;
    }
    retriever.release();
    return null;
}

From source file:Main.java

private static void saveMetadata(MediaMetadataRetriever metadataRetriever, HashMap<String, String> metadata,
        int metadataKey) {
    String value = metadataRetriever.extractMetadata(metadataKey);
    if (value != null)
        metadata.put(Integer.toString(metadataKey), value);
}

From source file:Main.java

public static long getVideoDurationInMillis(String videoFile) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(videoFile);//from   ww w .j  ava2s  . c  o  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 {//ww  w  . j  a  v  a  2  s  .  co  m
        mmr.setDataSource(videoUrl);
    }
    return Long.parseLong(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
}

From source file:de.lebenshilfe_muenster.uk_gebaerden_muensterland.sign_video_view.AbstractSignVideoFragment.java

private void setVideoViewDimensionToMatchVideoMetadata(VideoView videoView, Uri uri) {
    String metadataVideoWidth;/*from  ww w. jav  a 2s .  c  o  m*/
    String metadataVideoHeight;
    try {
        final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
        metaRetriever.setDataSource(getActivity(), uri);
        metadataVideoWidth = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
        metadataVideoHeight = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
        metaRetriever.release();
        Validate.notEmpty(metadataVideoWidth);
        Validate.notEmpty(metadataVideoHeight);
    } catch (NullPointerException | IllegalArgumentException ex) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_2) + ex.getLocalizedMessage(), ex);
    }
    if (null == metadataVideoWidth) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_3));
    }
    if (null == metadataVideoHeight) {
        throw new VideoSetupException(getActivity().getString(R.string.ASVF_4));
    }
    final double videoWidth = Double.valueOf(metadataVideoWidth);
    final double videoHeight = Double.valueOf(metadataVideoHeight);
    final double videoRatio = videoWidth / videoHeight;
    Log.d(TAG, String.format("videoWidth: %s, videoHeight: %s, videoRatio: %s", videoWidth, videoHeight,
            videoRatio));
    boolean isOrientationPortrait = Configuration.ORIENTATION_PORTRAIT == getResources()
            .getConfiguration().orientation;
    int displayHeight = getResources().getDisplayMetrics().heightPixels;
    int displayWidth = getResources().getDisplayMetrics().widthPixels;
    Log.d(TAG, String.format("displayHeight: %s, displayWidth: %s", displayHeight, displayWidth));
    final double desiredVideoWidth, desiredVideoHeight;
    if (isOrientationPortrait) {
        desiredVideoWidth = displayWidth * MAXIMUM_VIDEO_WIDTH_ON_PORTRAIT;
        desiredVideoHeight = 1 / (videoRatio / desiredVideoWidth);
        Log.d(TAG, String.format("OrientationPortrait: desiredVideoWidth: %s, desiredVideoHeight: %s",
                desiredVideoWidth, desiredVideoHeight));
    } else { // orientation is Landscape
        desiredVideoHeight = displayHeight * MAXMIMUM_VIDEO_HEIGHT_ON_LANDSCAPE;
        desiredVideoWidth = desiredVideoHeight * videoRatio;
        Log.d(TAG, String.format("OrientationLandscape: desiredVideoWidth: %s, desiredVideoHeight: %s",
                desiredVideoWidth, desiredVideoHeight));
    }
    final ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
    layoutParams.width = (int) desiredVideoWidth;
    layoutParams.height = (int) desiredVideoHeight;
}

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
 *///from   w  ww.  j a v a2 s.  c om
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: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   ww  w.  j a v  a 2 s .co  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.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();//from w  w w  . ja va 2s. c om

                    //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:com.android.camera.v2.uimanager.ThumbnailManager.java

private String getMimeType(String filePath) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    String mime = "image/jpeg";
    if (filePath != null) {
        try {/*from  w ww . j  av  a2  s . c  om*/
            retriever.setDataSource(filePath);
            mime = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
        } catch (IllegalStateException e) {
            return mime;
        } catch (IllegalArgumentException e) {
            return mime;
        } catch (RuntimeException e) {
            return mime;
        }
    }
    LogHelper.i(TAG, "[getMimeType] mime = " + mime);
    return mime;
}