List of usage examples for android.media MediaMetadataRetriever MediaMetadataRetriever
public MediaMetadataRetriever()
From source file:com.appdevper.mediaplayer.app.MediaNotificationManager.java
private Bitmap downloadBitmap(String mediaId) { String url = MusicProvider.getInstance().getMusic(mediaId) .getString(MusicProviderSource.CUSTOM_METADATA_TRACK_SOURCE); final MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever(); metaRetriever.setDataSource(url, new HashMap<String, String>()); try {/*from w w w .ja v a2 s . c o m*/ final byte[] art = metaRetriever.getEmbeddedPicture(); return BitmapFactory.decodeByteArray(art, 0, art.length); } catch (Exception e) { Log.d(TAG, "Couldn't create album art: " + e.getMessage()); return BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art); } }
From source file:com.almalence.googsharing.Thumbnail.java
private static Bitmap createVideoThumbnail(String filePath, FileDescriptor fd, int targetWidth) { Bitmap bitmap = null;// w w w .jav a 2 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.aengbee.android.leanback.ui.VideoDetailsFragment.java
public int getDurationVideo(File videoFile) { MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(getActivity(), Uri.fromFile(videoFile)); String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); int sec = (int) Long.parseLong(time) / 1000; return sec;/* w w w. j a v a 2 s .c o m*/ }
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 a2 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(); }//from w w w . j a v a 2 s. c om } 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.xperia64.timidityae.MusicService.java
@SuppressLint("NewApi") public void play() { if (playList != null && currSongNumber >= 0) { shouldAdvance = false;//from ww w. j a va 2 s . co m death = true; fullStop = false; stop(); death = false; Globals.shouldRestore = true; while (!death && ((Globals.isPlaying == 0 || JNIHandler.alternativeCheck == 333333))) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } if (!death) { MediaMetadataRetriever mmr = new MediaMetadataRetriever(); String tmpTitle; Globals.currArt = null; final int songIndex; if (shuffleMode == 1) { songIndex = realSongNumber = shuffledIndices.get(currSongNumber); } else { songIndex = realSongNumber = currSongNumber; } try { mmr.setDataSource(playList.get(songIndex)); tmpTitle = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); if (tmpTitle != null) { if (TextUtils.isEmpty(tmpTitle)) tmpTitle = playList.get(songIndex) .substring(playList.get(songIndex).lastIndexOf('/') + 1); } else { tmpTitle = playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/') + 1); } } catch (RuntimeException e) { tmpTitle = playList.get(songIndex).substring(playList.get(songIndex).lastIndexOf('/') + 1); } boolean goodart = false; if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD_MR1) // Please work { try { byte[] art = mmr.getEmbeddedPicture(); if (art != null) { Globals.currArt = BitmapFactory.decodeByteArray(art, 0, art.length); goodart = Globals.currArt != null; } } catch (Exception e) { } } if (!goodart) { String goodPath = playList.get(songIndex).substring(0, playList.get(songIndex).lastIndexOf('/') + 1) + "folder.jpg"; if (new File(goodPath).exists()) { try { Globals.currArt = BitmapFactory.decodeFile(goodPath); } catch (RuntimeException e) { } } else { // Try albumart.jpg goodPath = playList.get(songIndex).substring(0, playList.get(songIndex).lastIndexOf('/') + 1) + "AlbumArt.jpg"; if (new File(goodPath).exists()) { try { Globals.currArt = BitmapFactory.decodeFile(goodPath); } catch (RuntimeException e) { // } } } } if (shouldDoWidget) { Intent intent = new Intent(this, TimidityAEWidgetProvider.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); // Use an array and EXTRA_APPWIDGET_IDS instead of AppWidgetManager.EXTRA_APPWIDGET_ID, // since it seems the onUpdate() is only fired on that: ids = AppWidgetManager.getInstance(getApplication()) .getAppWidgetIds(new ComponentName(getApplication(), TimidityAEWidgetProvider.class)); //intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); intent.putExtra("com.xperia64.timidityae.timidityaewidgetprovider.onlyart", true); sendBroadcast(intent); } Intent new_intent = new Intent(); new_intent.setAction(getResources().getString(R.string.ta_rec)); new_intent.putExtra(getResources().getString(R.string.ta_cmd), 6); sendBroadcast(new_intent); currTitle = tmpTitle; shouldAdvance = true; paused = false; final int x = JNIHandler.play(playList.get(songIndex)); if (x != 0) { switch (x) { case -1: handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_fnf), Toast.LENGTH_SHORT).show(); } }); break; case -3: handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), "Error initializing AudioTrack. Try decreasing the buffer size.", Toast.LENGTH_LONG).show(); } }); break; case -9: handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), getResources().getString(R.string.srv_loading), Toast.LENGTH_SHORT).show(); } }); break; default: handler.post(new Runnable() { @Override public void run() { Toast.makeText(getApplicationContext(), String.format(getResources().getString(R.string.srv_unk), x), Toast.LENGTH_SHORT).show(); } }); break; } Globals.isPlaying = 1; JNIHandler.type = true; shouldAdvance = false; JNIHandler.paused = false; stop(); } else { updateNotification(currTitle, paused); new Thread(new Runnable() { public void run() { while (!death && ((Globals.isPlaying == 1 && shouldAdvance))) { if (JNIHandler.alternativeCheck == 555555) death = true; //System.out.println(String.format("alt check: %d death: %s isplaying: %d shouldAdvance: %s seekBarReady: %s",JNIHandler.alternativeCheck,death?"true":"false",Globals.isPlaying,shouldAdvance?"true":"false",JNIHandler.seekbarReady?"true":"false")); try { Thread.sleep(10); } catch (InterruptedException e) { } } if (!death) { Intent new_intent = new Intent(); new_intent.setAction(getResources().getString(R.string.ta_rec)); new_intent.putExtra(getResources().getString(R.string.ta_cmd), 0); new_intent.putExtra(getResources().getString(R.string.ta_startt), JNIHandler.maxTime); new_intent.putExtra(getResources().getString(R.string.ta_songttl), currTitle); new_intent.putExtra(getResources().getString(R.string.ta_filename), playList.get(songIndex)); new_intent.putExtra("stupidNumber", songIndex); sendBroadcast(new_intent); } if (new File(playList.get(songIndex) + ".def.tcf").exists() || new File(playList.get(songIndex) + ".def.tzf").exists()) { String suffix; if (new File(playList.get(songIndex) + ".def.tcf").exists() && new File(playList.get(songIndex) + ".def.tzf").exists()) { suffix = (Globals.compressCfg ? ".def.tzf" : ".def.tcf"); } else if (new File(playList.get(songIndex) + ".def.tcf").exists()) { suffix = ".def.tcf"; } else { suffix = ".def.tzf"; } JNIHandler.shouldPlayNow = false; JNIHandler.currTime = 0; while (Globals.isPlaying == 0 && !death && shouldAdvance && !JNIHandler.dataWritten) { try { Thread.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); } } Intent new_intent = new Intent(); // silly, but should be done async. I think. new_intent.setAction(getResources().getString(R.string.msrv_rec)); new_intent.putExtra(getResources().getString(R.string.msrv_cmd), 17); new_intent.putExtra(getResources().getString(R.string.msrv_infile), playList.get(songIndex) + suffix); new_intent.putExtra(getResources().getString(R.string.msrv_reset), true); sendBroadcast(new_intent); } while (!death && (((Globals.isPlaying == 0 || JNIHandler.alternativeCheck == 333333) && shouldAdvance))) { try { Thread.sleep(25); } catch (InterruptedException e) { } } if (shouldAdvance && !death) { shouldAdvance = false; new Thread(new Runnable() { public void run() { if (playList.size() > 1 && (((songIndex + 1 < playList.size() && loopMode == 0)) || loopMode == 1)) { next(); } else if (loopMode == 2 || playList.size() == 1) { play(); } else if (loopMode == 0) { Globals.hardStop = true; Intent new_intent = new Intent(); new_intent.setAction(getResources().getString(R.string.ta_rec)); new_intent.putExtra(getResources().getString(R.string.ta_cmd), 5); new_intent.putExtra(getResources().getString(R.string.ta_pause), false); sendBroadcast(new_intent); } } }).start(); } } }).start(); } } } }
From source file:com.netcompss.ffmpeg4android_client.BaseWizard.java
public String createVideoThumbnail(String fDescriptor) { Bitmap thumb = null;/*ww w . j av 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:androidx.media.widget.VideoView2.java
private void openVideo(Uri uri, Map<String, String> headers) { resetPlayer();/*from w w w . jav a 2 s . co m*/ if (isRemotePlayback()) { // TODO (b/77158231) // mRoutePlayer.openVideo(dsd); return; } try { Log.d(TAG, "openVideo(): creating new MediaPlayer instance."); mMediaPlayer = new MediaPlayer(); mSurfaceView.setMediaPlayer(mMediaPlayer); mTextureView.setMediaPlayer(mMediaPlayer); mCurrentView.assignSurfaceToMediaPlayer(mMediaPlayer); final Context context = getContext(); // TODO: Add timely firing logic for more accurate sync between CC and video frame // mSubtitleController = new SubtitleController(context); // mSubtitleController.registerRenderer(new ClosedCaptionRenderer(context)); // mSubtitleController.setAnchor((SubtitleController.Anchor) mSubtitleView); mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnInfoListener(mInfoListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = -1; mMediaPlayer.setDataSource(getContext(), uri, headers); mMediaPlayer.setAudioAttributes(mAudioAttributes); // mMediaPlayer.setOnSubtitleDataListener(mSubtitleListener); // we don't set the target state here either, but preserve the // target state that was there before. mCurrentState = STATE_PREPARING; mMediaPlayer.prepareAsync(); // Save file name as title since the file may not have a title Metadata. mTitle = uri.getPath(); String scheme = uri.getScheme(); if (scheme != null && scheme.equals("file")) { mTitle = uri.getLastPathSegment(); } mRetriever = new MediaMetadataRetriever(); mRetriever.setDataSource(getContext(), uri); if (DEBUG) { Log.d(TAG, "openVideo(). mCurrentState=" + mCurrentState + ", mTargetState=" + mTargetState); } } catch (IOException | IllegalArgumentException ex) { Log.w(TAG, "Unable to open content: " + uri, ex); mCurrentState = STATE_ERROR; mTargetState = STATE_ERROR; mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, MediaPlayer.MEDIA_ERROR_IO); } }
From source file:com.keylesspalace.tusky.activity.ComposeActivity.java
private void pickMedia(Uri uri, long mediaSize) { ContentResolver contentResolver = getContentResolver(); if (mediaSize == MEDIA_SIZE_UNKNOWN) { displayTransientError(R.string.error_media_upload_opening); return;//from w ww . ja v a 2 s . c o m } String mimeType = contentResolver.getType(uri); if (mimeType != null) { String topLevelType = mimeType.substring(0, mimeType.indexOf('/')); switch (topLevelType) { case "video": { if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) { displayTransientError(R.string.error_media_upload_size); return; } if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) { displayTransientError(R.string.error_media_upload_image_or_video); return; } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, uri); Bitmap source = retriever.getFrameAtTime(); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128); source.recycle(); addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize); break; } case "image": { InputStream stream; try { stream = contentResolver.openInputStream(uri); } catch (FileNotFoundException e) { displayTransientError(R.string.error_media_upload_opening); return; } Bitmap source = BitmapFactory.decodeStream(stream); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, 128, 128); source.recycle(); try { if (stream != null) { stream.close(); } } catch (IOException e) { bitmap.recycle(); displayTransientError(R.string.error_media_upload_opening); return; } addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize); break; } default: { displayTransientError(R.string.error_media_upload_type); break; } } } else { displayTransientError(R.string.error_media_upload_type); } }
From source file:com.fa.mastodon.activity.ComposeActivity.java
private void pickMedia(Uri uri, long mediaSize) { ContentResolver contentResolver = getContentResolver(); if (mediaSize == MEDIA_SIZE_UNKNOWN) { displayTransientError(R.string.error_media_upload_opening); return;/*from w w w .j a v a 2 s .c o m*/ } String mimeType = contentResolver.getType(uri); if (mimeType != null) { String topLevelType = mimeType.substring(0, mimeType.indexOf('/')); switch (topLevelType) { case "video": { if (mediaSize > STATUS_MEDIA_SIZE_LIMIT) { displayTransientError(R.string.error_media_upload_size); return; } if (mediaQueued.size() > 0 && mediaQueued.get(0).type == QueuedMedia.Type.IMAGE) { displayTransientError(R.string.error_media_upload_image_or_video); return; } MediaMetadataRetriever retriever = new MediaMetadataRetriever(); retriever.setDataSource(this, uri); Bitmap source = retriever.getFrameAtTime(); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE); source.recycle(); addMediaToQueue(QueuedMedia.Type.VIDEO, bitmap, uri, mediaSize); break; } case "image": { InputStream stream; try { stream = contentResolver.openInputStream(uri); } catch (FileNotFoundException e) { displayTransientError(R.string.error_media_upload_opening); return; } Bitmap source = BitmapFactory.decodeStream(stream); Bitmap bitmap = ThumbnailUtils.extractThumbnail(source, THUMBNAIL_SIZE, THUMBNAIL_SIZE); source.recycle(); try { if (stream != null) { stream.close(); } } catch (IOException e) { bitmap.recycle(); displayTransientError(R.string.error_media_upload_opening); return; } addMediaToQueue(QueuedMedia.Type.IMAGE, bitmap, uri, mediaSize); break; } default: { displayTransientError(R.string.error_media_upload_type); break; } } } else { displayTransientError(R.string.error_media_upload_type); } }