Playing tunes by ear can seem mysterious but it can actually be a logical process. Learn the process and train your ears for it, and playing by ear will no longer seem like a mystery!
There are two main approaches to playing melodies by ear: using intervals or using solfa.
An "interval" is the distance in pitch between two notes. You can learn to recognise different types of interval which lets you "measure" pitch distances by ear. Then when you hear the notes in a melody you understand how far apart they all are, and can play them back by ear.
"Solfa" is a powerful framework for naming the notes of the scale. You can train your ears to recognise each note by its solfa name, so that when you hear a melody you immediately know where each note belongs in the scale, and so can play it back on your instrument.
Both approaches work well, and can even be combined. To begin learning to play melodies by ear, simply choose one of these two approaches and start training! Don't worry, you can always change your decision later, or mix-and-match. All the ear training you do will build valuable skills, even if you change approach along the way.
Learn more about intervals at Musical U
Learn more about solfa at Musical U