MediaMetadataRetriever Class in Android with Examples

18 Feb, 2021
anMediaMetadataRetriever class provides a unified interface for retrieving frames and metadata from an input media file. It is located under android.media package. For example: retrieving song name, artist name, width or height of the video, video format/mime-type, duration of media, media modified date, etc. Constants/Keys provided by MediaMetadataRetriever class are plentiful. These constants are used to retrieve media information. Although, the work done by many of the Constants is obvious from their name, here is a small description of each constant present in MediaMetadataRetriever class.
Constant Type
Constant Name
Description
Constant Type
Constant Name
Description
Method Type
Methods
extractMetadata(int keyCode)
Call this method after setDataSource().
getEmbeddedPicture()
Call this method after setDataSource().
getFrameAtTime(long timeUs, int option)
Call this method after setDataSource().
getFrameAtTime(long timeUs)
Call this method after setDataSource().
getFrameAtTime()
Call this method after setDataSource().
release()
Call it when one is done with the object.
This method releases the memory allocated internally.
setDataSource(FileDescriptor fd, long offset, long length)
Sets the data source (FileDescriptor) to use.
setDataSource(String path)
Sets the data source (file pathname) to use.
setDataSource(FileDescriptor fd)
Sets the data source (FileDescriptor) to use.
setDataSource(Context context, Uri uri)
Sets the data source as a content Uri.
Close()
Closes this resource, relinquishing any underlying resources. 
This method is invoked automatically on objects managed by 
the try-with-resources statement.
1. Get mp3 duration
Here is the sample code snippet in Java to get the mp3 duration. 
Java
// load data file// filePath is of type String which holds the path of fileMediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();metaRetriever.setDataSource(filePath);  // get mp3 infoString duration = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);long dur = Long.parseLong(duration);  // convert duration to minute:secondsString seconds = String.valueOf((dur % 60000) / 1000);String minutes = String.valueOf(dur / 60000);String out = minutes + ":" + seconds;if (seconds.length() == 1) {    txtTime.setText("0" + minutes + ":0" + seconds);}else {    txtTime.setText("0" + minutes + ":" + seconds);}  // close objectmetaRetriever.release();
2. Detect the orientation of the video
Below is a sample video
Here is the sample code snippet in Java to detect the orientation of the video
Java
MediaMetadataRetriever m = new MediaMetadataRetriever();  // load data filem.setDataSource(path);  // getting the bitmap of a frame from videoBitmap thumbnail = m.getFrameAtTime();  if (Build.VERSION.SDK_INT >= 17) {    String s = m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);}  // Another way of determining whether the video is Landscape or portraitMediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(inputPath);video_width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));video_height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));  // close objectretriever.release();  // If the width is bigger than the height then it means that// the video was taken in landscape mode and vice versa.if ((video_width > video_height)) {    // landscape}else {    // portrait}
3. Setting up the Album cover and Album title in a Music App
Below is a sample image
Here is the sample code snippet in Java to setting up the Album cover and Album title in a Music App.
Java
MediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(filePath);  // getting the embedded picture from mediabyte[] art = retriever.getEmbeddedPicture();  if (art != null) {    // Convert the byte array to a bitmap    imgAlbum.setImageBitmap(BitmapFactory.decodeByteArray(art, 0, art.length));}else {    imgAlbum.setImageResource(R.drawable.no_image);}// close objectretriever.release();
4. Making a CropVideo Activity like TikTok
Below is a sample video
Here is the sample code snippet in Java to make a CropVideo Activity like TikTok.
Java
try {    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();    mediaMetadataRetriever.setDataSource(context, videoUri);      // Retrieve media data use microsecond    long interval = (endPosition - startPosition) / (totalThumbsCount - 1);    for (long i = 0; i < totalThumbsCount; ++i) {        long frameTime = startPosition + interval * i;        Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(frameTime * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);        if (bitmap == null)            continue;        try {            bitmap = Bitmap.createScaledBitmap(bitmap, THUMB_WIDTH, THUMB_HEIGHT, false);        }        catch (final Throwable t) {            t.printStackTrace();        }        // add bitmaps to the recyclerview here...    }    mediaMetadataRetriever.release();}catch (final Throwable e) {    Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);}
Note:
Always check for illegal filePath.Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap.The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key.When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned.setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming.
Always check for illegal filePath.
Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap.
The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key.
When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned.
setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming.
Reference link: https://developer.android.com/reference/android/media/MediaMetadataRetriever
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.