Android MediaMetadataRetriever wrong video height and width

2.6k views Asked by At

I want to retrieve height and width of video, I am using MediaMetadataRetriever class for this. It is working correct for most of the case, but for few case height and width are interchanged.

I think this might be happening because of orientation change.

My current code:

MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
        metaRetriever.setDataSource(videoPath);
        videoHeight = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
        videoWidth = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);

How can i get correct values? Thank you

2

There are 2 answers

0
Rohaitas Tanoli On

Thanks to the answer by Keith. Here is full java method.

    void getWidthAndHeightOfVideo(String filePath) {


    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
    retriever.setDataSource(filePath);

    String metaRotation = retriever.extractMetadata(METADATA_KEY_VIDEO_ROTATION);
    int rotation = metaRotation == null ? 0 : Integer.parseInt(metaRotation);
    
    String widthString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
    String heightString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
    
    if (rotation == 90 || rotation == 270) {
        videoWidth = Integer.parseInt(heightString);
        videoHeight = Integer.parseInt(widthString);
    } else {
        videoWidth = Integer.parseInt(widthString);
        videoHeight = Integer.parseInt(heightString);
    }
    
    Log.e(TAG, "getWidthAndHeightOfVideo: " + videoHeight + " AA " + videoWidth);
    
    try {
        retriever.release();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}
0
Keith Loughnane On

I've been trying to figure this out myself for the last day or so, I eventually had to solve it experimentally.

            File file = new File(path);
            if (file.exists()) {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(file.getAbsolutePath());
                String metaRotation = retriever.extractMetadata(METADATA_KEY_VIDEO_ROTATION);
                int rotation = metaRotation == null ? 0 : Integer.parseInt(metaRotation);
                Log.i("Test", "Rotation = " + rotation);
            }

If the rotation is 90 or 270 the width and height will be transposed.