Search code examples
androidvideoffmpegmediametadataretriever

Getting the aspect ratio of any video


I want to get the aspect ratio of nay video in android like (1:1, 9:16 etc). Currently i get the height and width of a video but i want the aspect ratio. Is this task is possible with Ffmpeg or MediaMetadataRetriever? If yes, then please give me some example code. If no, then please suggest me the other solutions.


Solution

  • The aspect ratio is just the ratio of the height to the width* - as you can get those I think what you are looking for is simply a way to reduce them to the lowest ratio.

    This is a common maths exercise - you divide each number by their greatest common divisor, which is the largest number which will divide into both numbers (https://en.wikipedia.org/wiki/Greatest_common_divisor).

    There is a nice example in Java using a recursive modulus division here you can use: https://stackoverflow.com/a/4009247/334402

    So in summary you:

    • get the height and width (e.g. 1500, 500)
    • get their greatest common divisor, gcd (500 in this example)
    • dived the gcd into both numbers and get your aspect ratio is its lowest terms (3:1 in this example)

    (*) Update. Actually @llogan's very good answer includes both SAR and DAR aspect ratios. Sample Aspect ratio, SAR, is the original source aspect ratio and Display Aspect Ratio is the aspect ration of the video as it is intended to be displayed. There is a third term you may see sometimes also, Pixel aspect ratio which is the DAR divided by the SAR. I suspect it is still the DAR you are interested in so the height and width approach you used still applies.