When sounds first enter the brain, they activate a region near the ears called the primary auditory cortex that starts processing sounds at their most basic level. The auditory cortex then passes on signals of its own to other regions, which can recognize more complex features of music, like rhythm, key changes and melody.
These music-processing regions may be continually looking for signals in the brain that they can interpret. When no sound is coming from the ears, the brain may still generate occasional, random impulses that the music-processing regions interpret as sound. They then try to match these impulses to memories of music, turning a few notes into a familiar melody.
For most people, these spontaneous signals may produce nothing more than a song that is hard to get out of the head.
Research into musical hallucinations is illuminating the phenomenon of the song that gets stuck in your head. My four-year-old was afflicted recently — he looked up from a construction project to say, in a bewildered tone, "Now all I can think about is Elvis."