Automatically creating a drone part from a given melody

If you want to automatically create a "drone part" to go with a melody (for example, for a MIDI file of bagpipe music) you can use the \dronify music function in this snippet.This function takes two arguments, a drone pitch and a melody, and returns the melody as follows:(1) the pitch of each note is changed to the drone pitch,(2) ties are added between all the notes for a continuous drone sound,(3) rests in the melody are mirrored by rests in the drone part.

\version "2.24.0"

% see also:  scm/define-music-types.scm

dronify =
#(define-music-function (drone-pitch melody)
  (ly:pitch? ly:music?)
  (let ((artics '())
        (prev-note-or-rest #{ #}))
    (music-map
     (lambda (m)
       (if (and (music-is-of-type? m 'note-event)
                (ly:pitch? (ly:music-property m 'pitch)))
           (begin
             (ly:music-set-property! m 'pitch drone-pitch)
             
             ;; if the previous note or rest was a note, add a tie articulation 
             ;; to it
             ;; don't overwrite its existing articulations
             (if (music-is-of-type? prev-note-or-rest 'note-event)
                 (begin
                   (set! 
                     artics 
                     (ly:music-property prev-note-or-rest 'articulations '()))
                   (ly:music-set-property! prev-note-or-rest 'articulations
                     (append artics (list (make-music 'TieEvent))))))))
             
       ;; store previous note or rest so a tie can be added "retroactively"
       (if (or (music-is-of-type? m 'note-event)
               (music-is-of-type? m 'rest-event)
               (music-is-of-type? m 'multi-measure-rest))
           (set! prev-note-or-rest m))
  
       m)
     melody)))

melody = \relative {
  | c'4 f8 g e4 \staccato r
  | \grace c4 f c'8 g \grace g a2
  | R1
  | c8 c c a c,2
}

\score {
  <<
    \melody
    \dronify g \melody
  >>
  \layout {}
  \midi {}
}