Fortunately there is (as you've noted) midi instruments for both regular trumpet and muted trumpet.
You can change between them just by placing:
\set Staff.midiInstrument = #"trumpet"
or
\set Staff.midiInstrument = #"muted trumpet"
in the music at any point.
But, to get the midi channel mapping to change with the midi instrument, you must tell LilyPond to map channels in this way, by placing:
\context { \Score midiChannelMapping = #'instrument }
in the midi block.
Here is a working example:
\version "2.23.6"
\language "english"
trumpet = {
\new Staff {
\set Staff.instrumentName =
\markup {
\center-column {
"Trumpet" \vspace #-0.3
\tiny\concat {"in B"\flat}
}
}
\transposition bf
\set Staff.midiInstrument = #"trumpet"
c'4 g' c'' g' |
R1^"con sord." |
\set Staff.midiInstrument = #"muted trumpet"
c'4 g' c''8 8 g'4 |
R1^"senza sord." |
\set Staff.midiInstrument = #"trumpet"
c'4 g' c'' g' |
c'1 |
}
}
\score {
\trumpet
\layout { }
\midi {
\context { \Score midiChannelMapping = #'instrument }
}
}
However, whether the program you are playing your midi file with knows what to do with a "muted trumpet" is another question.
For example if you import the midi file generated from the above into RealPlayer, the program will know what to do, and changes instrument sound at the right time as desired.
But if you import into MuseScore, it will recognise that there are two channels and separate them, but (unfortunately) give them both the same MuseScore instrument.* To get a muted trumpet sound in MuseScore you need to use the "Mute" text for the second instrument, which can be found in the text palette.
* This is because both "trumpet" and "muted trumpet" midi instruments are interpreted as just the "trumpet" MuseScore instrument. Muting is seen as applying an effect, rather than changing instruments (which kinda makes sense). Changing between other instruments (such and flute and piccolo, or oboe and english horn) won't have this problem.
midiInstrument
setting.