Example usage for android.media MediaMetadataRetriever setDataSource

List of usage examples for android.media MediaMetadataRetriever setDataSource

Introduction

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

Prototype

public void setDataSource(MediaDataSource dataSource) throws IllegalArgumentException 

Source Link

Document

Sets the data source (MediaDataSource) to use.

Usage

From source file:com.almalence.googsharing.Thumbnail.java

private static Bitmap createVideoThumbnail(String filePath, FileDescriptor fd, int targetWidth) {
    Bitmap bitmap = null;//from w ww. ja  v a2  s  .c o m
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        if (filePath != null) {
            retriever.setDataSource(filePath);
        } else {
            retriever.setDataSource(fd);
        }
        bitmap = retriever.getFrameAtTime(-1);
    } catch (IllegalArgumentException ex) {
        // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
        // Assume this is a corrupt video file.
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
            // Ignore failures while cleaning up.
        }
    }
    if (bitmap == null)
        return null;

    // Scale down the bitmap if it is bigger than we need.
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    if (width > targetWidth) {
        float scale = (float) targetWidth / width;
        int w = Math.round(scale * width);
        int h = Math.round(scale * height);
        bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
    }
    return bitmap;
}

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
 *//*w ww .j a v  a  2s.  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.online.fullsail.SaveWebMedia.java

private Bitmap getVideoFrame(String uri) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {/*  ww w.j  a v a2s  .  c o  m*/
        if (Integer.parseInt(Build.VERSION.SDK) > Build.VERSION_CODES.GINGERBREAD) {
            retriever.setDataSource(uri);
            return retriever.getFrameAtTime();
        } else {
            retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
            retriever.setDataSource(uri);
            return retriever.captureFrame();
            // These items were handled by the custom android media class
            // Despite being marked errors, they compile without an issue
        }
    } catch (IllegalArgumentException ex) {
        ex.printStackTrace();
    } catch (RuntimeException ex) {
        ex.printStackTrace();
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
        }
    }
    return null;
}

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 www . java 2 s  .  com*/
            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;
}

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

private void setNotPlayingSeekBarAndTime(Episode ep) {
    if (service == null) {
        return;/*from ww  w. j a  v a 2s . c  o 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());
    }
}

From source file:com.android.camera.manager.ThumbnailViewManager.java

private String getMimeType(String filePath) {
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    String mime = "image/jpeg";
    if (filePath != null) {
        try {/*w w w  . ja v  a 2 s. com*/
            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;
        }
    }
    Log.d(TAG, "[getMimeType] mime = " + mime);
    return mime;
}

From source file:com.aniruddhc.acemusic.player.NowPlayingActivity.PlaylistPagerFlippedFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_playlist_pager_flipped, container,
            false);//from  w w w . ja v  a2 s.c o m
    mContext = getActivity().getApplicationContext();
    mApp = (Common) mContext;

    ratingBar = (RatingBar) rootView.findViewById(R.id.playlist_pager_flipped_rating_bar);
    lyricsRelativeLayout = (RelativeLayout) rootView.findViewById(R.id.lyricsRelativeLayout);
    lyricsTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_lyrics);
    headerTextView = (TextView) rootView.findViewById(R.id.playlist_pager_flipped_title);
    noLyricsFoundText = (TextView) rootView.findViewById(R.id.no_embedded_lyrics_found_text);

    lyricsTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    lyricsTextView
            .setPaintFlags(lyricsTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    headerTextView.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    headerTextView
            .setPaintFlags(headerTextView.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    noLyricsFoundText.setTypeface(TypefaceHelper.getTypeface(mContext, "RobotoCondensed-Light"));
    noLyricsFoundText.setPaintFlags(
            noLyricsFoundText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    lyricsRelativeLayout.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View arg0) {
            //Fire a broadcast that notifies the PlaylistPager to update flip back to the album art.
            Intent intent = new Intent(broadcastMessage);
            intent.putExtra("MESSAGE", broadcastMessage);

            //Initialize the local broadcast manager.
            localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
            localBroadcastManager.sendBroadcast(intent);

            return true;
        }

    });

    //Get the file path of the current song.
    String updatedSongTitle = "";
    String updatedSongArtist = "";
    String songFilePath = "";
    String songId = "";
    MediaMetadataRetriever mmdr = new MediaMetadataRetriever();
    tempCursor = mApp.getService().getCursor();
    tempCursor.moveToPosition(
            mApp.getService().getPlaybackIndecesList().get(mApp.getService().getCurrentSongIndex()));
    if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
        //Retrieve the info from the file's metadata.
        songFilePath = tempCursor.getString(tempCursor.getColumnIndex(null));
        mmdr.setDataSource(songFilePath);

        updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
        updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);

    } else {
        /* Check if the cursor has the SONG_FILE_PATH column. If it does, we're dealing 
         * with the SONGS table. If not, we're dealing with the PLAYLISTS table. We'll 
         * retrieve data from the appropriate columns using this info. */
        if (tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH) == -1) {
            //We're dealing with the Playlists table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.PLAYLIST_FILE_PATH));
            mmdr.setDataSource(songFilePath);

            updatedSongTitle = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
            updatedSongArtist = mmdr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
        } else {
            //We're dealing with the songs table.
            songFilePath = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_FILE_PATH));
            updatedSongTitle = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_TITLE));
            updatedSongArtist = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ARTIST));
            songId = tempCursor.getString(tempCursor.getColumnIndex(DBAccessHelper.SONG_ID));
        }

    }

    headerTextView.setText(updatedSongTitle + " - " + updatedSongArtist);
    ratingBar.setStepSize(1);
    int rating = mApp.getDBAccessHelper().getSongRating(songId);
    ratingBar.setRating(rating);

    //Get the rating value for the song.
    AudioFile audioFile = null;
    File file = null;
    try {
        audioFile = null;
        file = new File(songFilePath);
        try {
            audioFile = AudioFileIO.read(file);
        } catch (CannotReadException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (org.jaudiotagger.tag.TagException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ReadOnlyFileException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (InvalidAudioFrameException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        final AudioFile finalizedAudioFile = audioFile;
        final String finalSongFilePath = songFilePath;
        final String finalSongId = songId;
        ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                //Change the rating in the DB and the actual audio file itself.

                Log.e("DEBUG", ">>>>>RATING: " + rating);

                try {
                    Tag tag = finalizedAudioFile.getTag();
                    tag.addField(FieldKey.RATING, "" + ((int) rating));
                } catch (KeyNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (FieldDataInvalidException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("DEBUG", ">>>>>>>RATING FIELD NOT FOUND");
                }

                try {
                    finalizedAudioFile.commit();
                } catch (CannotWriteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mApp.getDBAccessHelper().setSongRating(finalSongId, (int) rating);

            }

        });

        //Check if the audio file has any embedded lyrics.
        String lyrics = null;
        try {
            Tag tag = audioFile.getTag();
            lyrics = tag.getFirst(FieldKey.LYRICS);

            if (lyrics == null || lyrics.isEmpty()) {
                lyricsTextView.setVisibility(View.GONE);
                noLyricsFoundText.setVisibility(View.VISIBLE);
                return rootView;
            }

            //Since the song has embedded lyrics, display them in the layout.
            lyricsTextView.setVisibility(View.VISIBLE);
            noLyricsFoundText.setVisibility(View.GONE);
            lyricsTextView.setText(lyrics);

        } catch (Exception e) {
            e.printStackTrace();
            lyricsTextView.setVisibility(View.GONE);
            noLyricsFoundText.setVisibility(View.VISIBLE);
            return rootView;
        }
    } catch (Exception e) {
        e.printStackTrace();
        //Can't do much here.
    }

    return rootView;
}

From source file:com.aimfire.gallery.service.MovieProcessor.java

@Override
protected void onHandleIntent(Intent intent) {
    /*/*  w  w w .  ja v a 2  s.co m*/
     * Obtain the FirebaseAnalytics instance.
     */
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);

    boolean[] result = new boolean[] { false, false };
    String previewPath = null;
    String thumbPath = null;
    String configPath = null;
    String convertFilePath = null;

    String exportL = MainConsts.MEDIA_3D_RAW_PATH + "L.png";
    String exportR = MainConsts.MEDIA_3D_RAW_PATH + "R.png";

    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    Bundle extras = intent.getExtras();
    if (extras == null) {
        if (BuildConfig.DEBUG)
            Log.e(TAG, "onHandleIntent: error, wrong parameter");
        FirebaseCrash.report(new Exception("onHandleIntent: error, wrong parameter"));
        return;
    }

    String filePathL = extras.getString("lname");
    String filePathR = extras.getString("rname");
    String cvrNameNoExt = MediaScanner.getProcessedCvrName((new File(filePathL)).getName());

    if (BuildConfig.DEBUG)
        Log.d(TAG, "onHandleIntent:left file=" + filePathL + ", right file=" + filePathR);

    String creatorName = extras.getString("creator");
    String creatorPhotoUrl = extras.getString("photo");

    float scale = extras.getFloat(MainConsts.EXTRA_SCALE);

    /*
     * if left/right videos were taken using front facing camera,
     * they need to be swapped when generating sbs 
     */
    int facing = extras.getInt(MainConsts.EXTRA_FACING);
    boolean isFrontCamera = (facing == Camera.CameraInfo.CAMERA_FACING_FRONT) ? true : false;

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    Bitmap bitmapL = null;
    Bitmap bitmapR = null;

    long frameTime = FIRST_KEYFRAME_TIME_US;
    if (BuildConfig.DEBUG)
        Log.d(TAG, "extract frame from left at " + frameTime / 1000 + "ms");

    try {
        long startUs = SystemClock.elapsedRealtimeNanos() / 1000;

        FileInputStream inputStreamL = new FileInputStream(filePathL);
        retriever.setDataSource(inputStreamL.getFD());
        inputStreamL.close();

        bitmapL = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        FileInputStream inputStreamR = new FileInputStream(filePathR);
        retriever.setDataSource(inputStreamR.getFD());
        inputStreamR.close();

        bitmapR = retriever.getFrameAtTime(frameTime, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);

        retriever.release();

        long stopUs = SystemClock.elapsedRealtimeNanos() / 1000;
        if (BuildConfig.DEBUG)
            Log.d(TAG, "retrieving preview frames took " + (stopUs - startUs) / 1000 + "ms");

        if ((bitmapL != null) && (bitmapR != null)) {
            saveFrame(bitmapL, exportL);
            saveFrame(bitmapR, exportR);
        } else {
            reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                    ERROR_EXTRACT_SYNC_FRAME_ERROR);
            return;
        }

        previewPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpeg";

        result = p.getInstance().f1(exportL, exportR, previewPath, scale, isFrontCamera);
    } catch (Exception ex) {
        retriever.release();
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SYNC_FRAME_EXCEPTION);
        return;
    }

    if (!result[0]) {
        reportError(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()),
                ERROR_EXTRACT_SIMILARITY_MATRIX);

        File leftFrom = (new File(filePathL));
        File rightFrom = (new File(filePathR));
        File leftExportFrom = (new File(exportL));
        File rightExportFrom = (new File(exportR));

        if (!BuildConfig.DEBUG) {
            leftFrom.delete();
            rightFrom.delete();

            leftExportFrom.delete();
            rightExportFrom.delete();
        } else {
            File leftTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftFrom.getName());
            File rightTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightFrom.getName());

            leftFrom.renameTo(leftTo);
            rightFrom.renameTo(rightTo);

            File leftExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + leftExportFrom.getName());
            File rightExportTo = new File(MainConsts.MEDIA_3D_DEBUG_PATH + rightExportFrom.getName());

            leftExportFrom.renameTo(leftExportTo);
            rightExportFrom.renameTo(rightExportTo);
        }
    } else {
        double[] similarityMat = p.getInstance().g();

        String configData = similarityMat[0] + " " + similarityMat[1] + " " + similarityMat[2] + " "
                + similarityMat[3] + " " + similarityMat[4] + " " + similarityMat[5];

        if (result[1]) {
            convertFilePath = filePathR;
        } else {
            convertFilePath = filePathL;
        }

        configPath = createConfigFile(convertFilePath, configData);

        /*
         * save the thumbnail
         */
        if (bitmapL != null) {
            thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + cvrNameNoExt + ".jpg";
            saveThumbnail(bitmapL, thumbPath);

            MediaScanner.insertExifInfo(thumbPath, "name=" + creatorName + "photourl=" + creatorPhotoUrl);
        }

        createZipFile(filePathL, filePathR, configPath, thumbPath, previewPath);

        /*
         * let CamcorderActivity know we are done.
         */
        reportResult(MediaScanner.getProcessedCvrPath((new File(filePathL)).getName()));
    }

    /*
     * paranoia
     */
    if (bitmapL != null) {
        bitmapL.recycle();
    }
    if (bitmapR != null) {
        bitmapR.recycle();
    }

    (new File(exportL)).delete();
    (new File(exportR)).delete();
}

From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java

public String createVideoThumbnail(String fDescriptor) {
    Bitmap thumb = null;/*from   w w w  .j  a  v a 2  s .co m*/
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    try {
        retriever.setDataSource(fDescriptor);
        thumb = retriever.getFrameAtTime(-1);
        int width = thumb.getWidth();
        int height = thumb.getHeight();
        int max = Math.max(width, height);
        if (max > 512) {
            float scale = 512f / max;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            thumb = Bitmap.createScaledBitmap(thumb, w, h, true);
        }

        FileOutputStream fos = null;
        String extr = Environment.getExternalStorageDirectory().toString();
        File mFolder = new File(extr + "/CHURCH");
        if (!mFolder.exists()) {
            mFolder.mkdir();
        } else {
            mFolder.delete();
            mFolder.mkdir();
        }

        String s = "churchthumbs.png";

        video_thumbpath = new File(mFolder.getAbsolutePath(), s);
        returnPath = video_thumbpath.getAbsolutePath();

        try {
            fos = new FileOutputStream(video_thumbpath);
            thumb.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }

    } catch (IllegalArgumentException ex) {
        // Assume this is a corrupt video file
        Log.e("e", "Failed to create video thumbnail for file description: " + fDescriptor.toString());
    } catch (RuntimeException ex) {
        // Assume this is a corrupt video file.
        Log.e("e", "Failed to create video thumbnail for file description: " + fDescriptor.toString());
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
            // Ignore failures while cleaning up.
        }
    }
    return returnPath;
}

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

/**
 * Take snapshots of a video file// ww  w.  j  a  va 2s .  c om
 *
 * @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) {
                }
            }
        }
    });
}