Music finds it evolutionary beneficial so songs have evolved to become earworms that you'll sometimes spread to other hosts. It's not really detrimental to humans, so there's no impetus to weed it out.
Hearing rhythmic sounds in your head could arise from prehistoric humans running in groups together- music / songs on repeat helps synchronize pace and maintain tight formation.
The Bipedal Hypothesis:
+ the world ends and starts as music.
+ the resonance of the cavity of your inner ear adds to the suggested best-fit-auto-fit-auditory-consciousness-[memory] as qbrass pointed out.
+ birds must remember songs to communicate effectively, a lot of their understanding is based on the shape of their beaks and lungs. based on our "evolutionary shape" or "genetic fractal manifestations" our conch-like ears are good for resonating tones that could be beneficial to us (like mating calls)
+ from a linguistic evolution point of view, something that not only carries the soothing calm of a mother's voice but also helpful information becomes something worth repeating for sake of the individual and the species at large
+ typically people recall the lyrics to a song, or the vocal melody line, but people who play instruments can get bass or drum parts "stuck in their head" so evolutionarily speaking it is all about what your instrument of communication is (that coordinates sound and physical expressivity)
+ kaw!