Zillions of times. Usually it's in the moments when I've set up the mics and the drummer and I are just messing about, just warming up and making sure the mics are picking up. I've written or we've written so many bits that way. They're usually intros, born of quick jams. It never ceases to amaze them that I'll say, 'hey, that was neat ! I'm keeping that'.
Other times, when the guide guitar or bass has been recorded with the keeper drums or percussion and I'm about to lay down the keeper guitar or bass, I may change bits of what was originally meant to be there. The other week I was putting some guitar down to an already tracked piece. I was trying an experiment where I was going to record what was meant to be the intro, but with the varispeed slowed down so that I could do the chords in a different way {say it was a Dm, play it as a Bm, but slowed down by 3 semitones}. You can get really interesting sounds to each chord, like it was played in some esoteric position on the neck, somewhere I couldn't ordinarilly reach ! Anyway, I played some random chord positions, some of which I knew, some I just made up. Four chords, they went together beautifully and this became my intro and outro. I was able to craft a nice bass line to it. But it all happened spontaneously.
Back in September, I was experimenting with a suitcase as a bass drum {thank you, Moresound !}. My drummer friend was just off to Uni so it was a rushed session and we had a jam just to warm up. At one point, we hit this nice groove and the juices were flowing so I hit the footswitch and recorded about the last 4 minutes. It was just a 4 chord progression but it went through various moves, fast, slow, half time.......Had it been shit I would've just recorded over it but we liked it, despite it's imperfections. Then we recorded the song that we'd gotten together to record !
Over the next 5 or so months, I thought periodically about this jam piece and came up with 4 chord progressions which I intended to disperse throughout the song. But when I came to put something with the drums, I thought most of the progressions were crapola. Everything I tried seemed trite and predictable but eventually, I came up with a weird progression interspersed with one of the previously rejected parts and the original progression from the 'suitcase' jam. When I recorded it, I used a Y cable and played simultaneously through two amps {a line 6 spider and
a Fender Bassman 100} and miked them. I liked it. I should add that just before last christmas, I was in the shower when this melody hit me and I worked out some chords for it and added it to the end of this song.
Some songs are very definite, others 'evolve', literally.