For me it was repetition and PRACTICE, lots of it, but my inception of these habits were over 30 yrs ago.
I've had music lessons since I was about 8 yrs old so lots of this stuff has been ingrained and hard for me to explain.
Back in the old days, I'd put on the radio and just noodle along to whatever song was playing (with my guitar). Of course, I'm no savant, so lots of the noodling was rubbish, but over time I was able to play along with what I heard.
A few yrs later, I really wanted to learn 'Message In A Bottle' by The Police, but my guitar teacher refused (idiot! how DARE he deny me!) saying it was 'too complicated'. So adamant in proving him wrong, I recorded the song from the vinyl to a 90 min cassette tape, over and over on both sides, yes 90 mins of 'Message In A Bottle' - it was glorious...
After about a week of 2 hrs per day, I was able to get the whole song, note for note, by ear.
I showed my parents, some friends, and were amazed. Next lesson, I showed my guitar teacher. He was amazed but also angry because I had not only leapfrogged his lessons, but had taught myself m9, Add9 and 13th chords, which he seemed not to be prepared to understand, but 3 yrs of piano and music theory I was already well acquainted.
After that session, I ended my lessons with that teacher.
Moral of the story, there is lots of merit to knowing music theory, but you have to develop your own EAR, by training it, and this takes repetition, practice and time.
Nowadays, 30+ yrs later I can still play 'Message In A Bottle' note-for-note on piano, guitar, bass, ukulele and 5ths-tuned instruments, but with a baritone vocal range, I will never canary like Sting, so that dream will never be..../sigh/