List of usage examples for android.media MediaMetadataRetriever release
public native void release();
From source file:de.lebenshilfe_muenster.uk_gebaerden_muensterland.sign_video_view.AbstractSignVideoFragment.java
private void setVideoViewDimensionToMatchVideoMetadata(VideoView videoView, Uri uri) { String metadataVideoWidth;/*from www . j a va2 s. co 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.online.fullsail.SaveWebMedia.java
private Bitmap getVideoFrame(String uri) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try {//from w w w . jav a 2 s. c om 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.aimfire.gallery.service.MovieProcessor.java
@Override protected void onHandleIntent(Intent intent) { /*/*from w w w. ja va 2 s . c om*/ * 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.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 w w . j a va 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:org.runbuddy.tomahawk.activities.TomahawkMainActivity.java
private void handleIntent(Intent intent) { if (MediaStore.INTENT_ACTION_MEDIA_PLAY_FROM_SEARCH.equals(intent.getAction())) { intent.setAction(null);//from w w w.j a v a 2 s . c o m String playbackManagerId = getSupportMediaController().getExtras() .getString(PlaybackService.EXTRAS_KEY_PLAYBACKMANAGER); PlaybackManager playbackManager = PlaybackManager.getByKey(playbackManagerId); MediaPlayIntentHandler intentHandler = new MediaPlayIntentHandler( getSupportMediaController().getTransportControls(), playbackManager); intentHandler.mediaPlayFromSearch(intent.getExtras()); } if ("com.google.android.gms.actions.SEARCH_ACTION".equals(intent.getAction())) { intent.setAction(null); String query = intent.getStringExtra(SearchManager.QUERY); if (query != null && !query.isEmpty()) { DatabaseHelper.get().addEntryToSearchHistory(query); Bundle bundle = new Bundle(); bundle.putString(TomahawkFragment.QUERY_STRING, query); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC); FragmentUtils.replace(TomahawkMainActivity.this, SearchPagerFragment.class, bundle); } } if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) { intent.setAction(null); // if this Activity is being shown after the user clicked the notification if (mSlidingUpPanelLayout != null) { mSlidingUpPanelLayout.setPanelState(SlidingUpPanelLayout.PanelState.EXPANDED); } } if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) { intent.removeExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE); Bundle bundle = new Bundle(); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL); FragmentUtils.replace(this, PreferencePagerFragment.class, bundle); } if (intent.getData() != null) { final Uri data = intent.getData(); intent.setData(null); List<String> pathSegments = data.getPathSegments(); String host = data.getHost(); String scheme = data.getScheme(); if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk") || host.contains("beatsmusic.com") || host.contains("deezer.com") || host.contains("rdio.com") || host.contains("soundcloud.com")))) { PipeLine.get().lookupUrl(data.toString()); } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf")) || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) { TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) { @Override public void run() { Playlist pl = XspfParser.parse(data); if (pl != null) { final Bundle bundle = new Bundle(); bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } }); } } }; ThreadManager.get().execute(r); } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe") || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) { InstallPluginConfigDialog dialog = new InstallPluginConfigDialog(); Bundle args = new Bundle(); args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString()); dialog.setArguments(args); dialog.show(getSupportFragmentManager(), null); } else { String albumName; String trackName; String artistName; try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, data); albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); retriever.release(); } catch (Exception e) { Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage()); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { String msg = TomahawkApp.getContext().getString(R.string.invalid_file); Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show(); } }); return; } if (TextUtils.isEmpty(trackName) && pathSegments != null) { trackName = pathSegments.get(pathSegments.size() - 1); } Query query = Query.get(trackName, albumName, artistName, false); Result result = Result.get(data.toString(), query.getBasicTrack(), UserCollectionStubResolver.get()); float trackScore = query.howSimilar(result); query.addTrackResult(result, trackScore); Bundle bundle = new Bundle(); List<Query> queries = new ArrayList<>(); queries.add(query); Playlist playlist = Playlist.fromQueryList(IdGenerator.getSessionUniqueStringId(), "", "", queries); playlist.setFilled(true); playlist.setName(artistName + " - " + trackName); bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } } }
From source file:org.tomahawk.tomahawk_android.activities.TomahawkMainActivity.java
private void handleIntent(Intent intent) { if (SHOW_PLAYBACKFRAGMENT_ON_STARTUP.equals(intent.getAction())) { // if this Activity is being shown after the user clicked the notification if (mSlidingUpPanelLayout != null) { mSlidingUpPanelLayout.expandPanel(); }// w w w.jav a 2s . co m } if (intent.hasExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE)) { Bundle bundle = new Bundle(); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_STATIC_SMALL); FragmentUtils.replace(this, PreferencePagerFragment.class, bundle); } if (intent.getData() != null) { final Uri data = intent.getData(); intent.setData(null); List<String> pathSegments = data.getPathSegments(); String host = data.getHost(); String scheme = data.getScheme(); if ((scheme != null && (scheme.equals("spotify") || scheme.equals("tomahawk"))) || (host != null && (host.contains("spotify.com") || host.contains("hatchet.is") || host.contains("toma.hk") || host.contains("beatsmusic.com") || host.contains("deezer.com") || host.contains("rdio.com") || host.contains("soundcloud.com")))) { PipeLine.get().lookupUrl(data.toString()); } else if ((pathSegments != null && pathSegments.get(pathSegments.size() - 1).endsWith(".xspf")) || (intent.getType() != null && intent.getType().equals("application/xspf+xml"))) { TomahawkRunnable r = new TomahawkRunnable(TomahawkRunnable.PRIORITY_IS_INFOSYSTEM_HIGH) { @Override public void run() { Playlist pl = XspfParser.parse(data); if (pl != null) { final Bundle bundle = new Bundle(); bundle.putString(TomahawkFragment.PLAYLIST, pl.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } }); } } }; ThreadManager.get().execute(r); } else if (pathSegments != null && (pathSegments.get(pathSegments.size() - 1).endsWith(".axe") || pathSegments.get(pathSegments.size() - 1).endsWith(".AXE"))) { InstallPluginConfigDialog dialog = new InstallPluginConfigDialog(); Bundle args = new Bundle(); args.putString(InstallPluginConfigDialog.PATH_TO_AXE_URI_STRING, data.toString()); dialog.setArguments(args); dialog.show(getSupportFragmentManager(), null); } else { String albumName; String trackName; String artistName; try { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, data); albumName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM); artistName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST); trackName = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); retriever.release(); } catch (Exception e) { Log.e(TAG, "handleIntent: " + e.getClass() + ": " + e.getLocalizedMessage()); new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { String msg = TomahawkApp.getContext().getString(R.string.invalid_file); Toast.makeText(TomahawkApp.getContext(), msg, Toast.LENGTH_LONG).show(); } }); return; } if (TextUtils.isEmpty(trackName) && pathSegments != null) { trackName = pathSegments.get(pathSegments.size() - 1); } Query query = Query.get(trackName, albumName, artistName, false); Result result = Result.get(data.toString(), query.getBasicTrack(), UserCollectionStubResolver.get()); float trackScore = query.howSimilar(result); query.addTrackResult(result, trackScore); Bundle bundle = new Bundle(); List<Query> queries = new ArrayList<>(); queries.add(query); Playlist playlist = Playlist.fromQueryList(TomahawkMainActivity.getSessionUniqueStringId(), false, "", "", queries); bundle.putString(TomahawkFragment.PLAYLIST, playlist.getCacheKey()); bundle.putInt(TomahawkFragment.CONTENT_HEADER_MODE, ContentHeaderFragment.MODE_HEADER_DYNAMIC); FragmentUtils.replace(TomahawkMainActivity.this, PlaylistEntriesFragment.class, bundle); } } }
From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java
public String createVideoThumbnail(String fDescriptor) { Bitmap thumb = null;/* w ww . j ava2 s .c o 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//from w w 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) { } } } }); }
From source file:com.aimfire.demo.CamcorderActivity.java
private void generateThumbAndPreview(String filePath) { if (BuildConfig.DEBUG) Log.d(TAG, "generateThumbAndPreview"); String movieNameNoExt = MediaScanner.getMovieNameNoExt(filePath); String previewPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpeg"; String thumbPath = MainConsts.MEDIA_3D_THUMB_PATH + movieNameNoExt + ".jpg"; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); Bitmap bitmap = null;/*from w w w.j a va 2 s . co m*/ try { FileInputStream inputStream = new FileInputStream(filePath); retriever.setDataSource(inputStream.getFD()); inputStream.close(); bitmap = retriever.getFrameAtTime(0L, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); retriever.release(); if (bitmap != null) { FileOutputStream out = null; out = new FileOutputStream(previewPath); bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out); out.close(); Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, MainConsts.THUMBNAIL_SIZE, MainConsts.THUMBNAIL_SIZE); out = new FileOutputStream(thumbPath); thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, out); out.close(); } } catch (Exception e) { if (BuildConfig.DEBUG) Log.e(TAG, "generateThumbAndPreview: exception" + e.getMessage()); retriever.release(); FirebaseCrash.report(e); } }