A lot depends on the complexity of the music.How can a musician regenerate or rewrite the musical notes for a good song he just heard a few times ?
Most popular music has simple background harmony and rhythm patterns, which can often be learned or at least approximated almost instantly, so one basically picks up the melody accompanied by an obvious pattern. I used to do that on the guitar as a student (over 40 years ago). I've also for example played the violin along with folk music which I've never heard before, without any music in front of me, picking up the tune and harmonies as I go along (sometimes with a fractional delay or gap where the next move is not obvious), just following the patterns. It's just like singing along with something; you can guess a bit on the first verse and gradually get to know it as it goes on. If you know guitar chords, you can just hear the chord as a whole and play it automatically.
Even classical music has memorable patterns if you are familiar with the composer's style. I have on more than one occasion spotted an inconsistency (notes or phrasing) when sight-reading, for example when something on page 2 has a subtle difference from the equivalent passage on page 1. It's like someone said something just now, and now someone has said something similar but phrased it in a slightly different way, which is easily spotted.
In contrast, some of the Rachmaninoff I'm playing tonight is incredibly difficult to memorise; I always wonder how the composer knew that what appears to be cascades of random notes when played slowly would turn into amazingly rich and complex music at speed. The notes are far too fast to sight-read; I just have to keep playing them in different ways until my hands know them. An important trick is not to focus on too small a section for too long; it works much better if you keep moving on to new sections and don't come back for a few minutes, so that the pattern so far can get programmed into your longer term memory before the next iteration.