How did screaming as loud as you can become screaming "at the top of your lungs"?
Solution 1:
"Screaming at the top of your lungs" - I believe you can only scream aloud, when your lungs are filled to capacity or "to the brim", and hence "at the top of your lungs". The 'soundness' of our voice is directly related to the 'power of our lungs'.
As the air inside the lungs depletes, the pitch (of the sound) goes down.
Although there could be no rationale for idioms, that seems to be one. (Any upvotes for 'creativity' here?!)