pythonpython-3.xlilypond

How to change the clef of a container in mingus?


In mingus, the following code creates a single staff with a treble cleff and a C2 note.

from mingus.containers.bar import Bar
from mingus.containers.track import Track
from mingus.extra.lilypond import *
b = Bar("C")
t = Track(b)
t.add_notes("C-2")
sheet = from_Track(t)
to_png(sheet, "example1")

Alternatively, the following code creates two staves, each with a treble clef and a C5 and C2. respectively.

from mingus.containers.bar import Bar
from mingus.containers.track import Track
from mingus.containers.composition import Composition
from mingus.extra.lilypond import *
b1 = Bar("C")
b2 = Bar("C")
t1 = Track(b1)
t2 = Track(b2)
t1.add_notes("C-5")
t2.add_notes("C-2")
c = Composition()
c.add_track(t1)
c.add_track(t2)
sheet = from_Composition(c)
to_png(sheet, "example2")

How do I force mingus/lilypond to use a bass clef in either of these examples?

Thanks


Solution

  • Reading through the source, it doesn't look like it's supported!

    I was able to code up a work-around. It relies on using the Instrument class, where the clef property is supposed to be defined. Note that when you are defining your Track() objects, you should not be passing in Bar() objects, only Instrument() objects.

    My approach overrides the default from_Track() function in lilypond. It calls the original version of from_Track() and then makes sure to add whatever clef notation you want from here: https://lilypond.org/doc/v2.22/Documentation/notation/clef-styles . It's a simple patch, so there's no error-checking if you pick a bad clef style, so just make sure it's valid or else it'll revert to the default treble.

    Here's what I got working:

    from mingus.containers.bar import Bar
    from mingus.containers.instrument import Instrument
    from mingus.containers.track import Track
    from mingus.containers.composition import Composition
    import mingus.extra.lilypond as lilypond
    from_Track_Orig = lilypond.from_Track
    
    def from_Track(track):
        global from_Track_Orig
        result = from_Track_Orig(track)
        if isinstance(result,str) and track.instrument is not None and isinstance(track.instrument.clef,str):
            result = "%s \clef %s %s" % (result[:1], track.instrument.clef.split()[0], result[1:])
        return result
    lilypond.from_Track = from_Track
    
    i = Instrument()
    i.clef = 'bass'
    b1 = Bar("C")
    b2 = Bar("C")
    t1 = Track()
    t1.add_bar(b1)
    t2 = Track(i)
    t2.add_bar(b2)
    t1.add_notes("C-5")
    t2.add_notes("C-2")
    c = Composition()
    c.add_track(t1)
    c.add_track(t2)
    sheet = lilypond.from_Composition(c)
    lilypond.to_png(sheet, "example2")
    

    sheet music with treble and bass clefs