Some rando on quora sayeth
A tune stuck in your head is a phenomenon known as perseveration. The frontal cortex has a number of feedback loops that cycle through the basal ganglia. When tired, the inhibitory circuitry in the frontal lobe that control focus (think prevention of a “ooh shiny thing” moment) start to fatigue and regulation of those frontal lobe processes decrease. Unregulated cellular activity can create a positive feedback loop through the basal ganglia creating a thought or in your case, song, to be recurring and uncontrollable until you have some sort of sensory feedback to activate the cortical areas associated with the thought to provide the stimulus the brain was trying to mimic by perseverating the tune in the first place. For example, if you have a song stuck in your head, and you listen to the song, then it is no longer stuck in your head.