In my app a user selects a video from their camera roll. I need to check if that video is in a .mp4
container format and if it is not, I need to convert it to .mp4
.
Is there a modern way to do this today in Android?
Some of the things I tried:
I tried reading the mimeType from the File
with String mimeType = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE)
. But I think this may not be accurate because I am not actually looking at the codecs in the file. The mimeType could be inaccurate.
It looks like people are saying to use ffmpeg to convert the file to .mp4
, but the library listed is 7 years old and it seems overkill to use an external library for this. Is there a way modern way to do this with Android?
The MIME type reported by a MediaMetadataRetriever
is usually correct. If it says video/mp4
then the container is likely MP4.
You can double check it using a MediaExtractor
:
MediaExtractor extractor = new MediaExtractor();
extractor.setDataSource(context, fileUri, null);
PersistableBundle metrics = extractor.getMetrics();
String format = metrics.getString(MediaExtractor.MetricsConstants.FORMAT);
String mime = metrics.getString(MediaExtractor.MetricsConstants.MIME_TYPE);
Note that this doesn't tell you what codecs were used to compress the video / audio tracks (H.264
, H.265
, etc.). For this you would need to look at the MIME type of the track.
MediaFormat format = extractor.getTrackFormat(trackIndex);
A low-code solution for transcoding is to use a library such as Media3 Transformer.