Jump to content

Adding a Special Post Event Function to Implement Precise MIDI Velocity Value Control

From LilyPond wiki

This is a small hack to output MIDI file with precise velocity value control. This snippet adds a post event function \vel which enables you to set MIDI velocity value directly on any note event. This is accomplished by overriding dynamicAbsoluteVolumeFunction.

\version "2.24.0"

#(define-public (extended-dynamic-absolute-volume s)
  ;; debugging:
  ;(write s )(newline)
  (cond
   ((string? s )
    (default-dynamic-absolute-volume s))
   ((rational? s)
    (exact->inexact s))
   ((number? s )
    s)
   (else throw "this will never happen" )))

vel = #(define-event-function (velocity)(number?)
  #{ 
  	 \tweak stencil #'()
      $(make-music 
        'AbsoluteDynamicEvent 
        'text velocity 
        'direction 1)
  #})

\score {
  {
    c'\vel 0.2
    d'\vel 0.4
    e'\vel 0.6
    f'\vel 0.8
  }
  \layout { }
  \midi {
    \context {
      \Score
      dynamicAbsoluteVolumeFunction = #extended-dynamic-absolute-volume
    }
  }
}