Python music21 library create png from stream

3.5k Views Asked by At

I have a problem with generate png file from stream object in music21. I read documentation and I use ConverterLilypond to do this.

  chords = stream.Stream()

  d7 = chord.Chord(['D4', 'F4', 'A4', 'C5'])
  dmin7 = chord.Chord(['D4', 'F-4', 'A4', 'C5'])
  dmaj7 = chord.Chord(['D4', 'F#4', 'A4', 'C#5'])
  chords.append(d7)
  chords.append(dmin7)
  chords.append(dmaj7)
  conv = converter.subConverters.ConverterLilypond()
  conv.write(chords, fmt='lilypond', fp='file', subformats=['png'])

This code will generate png file, eps file count file, tex and texi file. Why? How can I generate only one file, PNG file?

When I try run this code in jupyter enough that I would use chords.show() to display image, but normally in the script the show generates a file, not a graphic.

EDIT:

Code with environment var

from music21 import *

us = environment.UserSettings()
us['lilypondPath'] = 'C:/Program Files (x86)/LilyPond/usr/bin/lilypond.exe'
us['musescoreDirectPNGPath'] = 'C:/Program Files (x86)/MuseScore 2/bin/MuseScore.exe'
us['musicxmlPath'] = 'C:/Program Files (x86)/MuseScore 2/bin/MuseScore.exe'

d7 = chord.Chord(['D4', 'F4', 'A4', 'C5'])

stream = stream.Stream()
stream.show('musicxml.png')
3

There are 3 best solutions below

5
Michael Scott Asato Cuthbert On BEST ANSWER

The best interface is by calling:

chords.show('lily.png')

which will run everything. But the Lilypond interface is not so strong, so better would be to install MuseScore and set the MusescoreDirectPNGPath in .music21rc to point to the mscore executable and the just call chords.show('musicxml.png') and it will do a much better translation via MusicXML.

2
Krzysztof Pieranski On

For all those who will struggle with displaying scores from music21 within Jupyter Notebook on Linux (e.g. Ubuntu), follow these steps:

1) Install MuseScore (https://musescore.org/en/download), e.g. using snappy :

sudo snap install musescore

2) Locate musescore in your filesystem:

whereis musescore

In my case it is "usr/bin/musescore".

3) Set environmental variable to tell music21 how can it locate music21. Do it in your Jupyter Notebook:

environment.set("musescoreDirectPNGPath", "/usr/bin/musescore")

4) Now you can use musescore to render music scores from music21:

bwv295 = corpus.parse('bach/bwv295')
bwv295.show()
0
fccoelho On

If you just want to generated pngs from musicXML files this is the easiest way. And since you can export any music21 stream to musicxml this is a valid way to get PNGs.

If you have Musescore installed, then from the console you just type:

$ mscore3 -o myscore.png -r 300 myscore.xml

-r lets you specify the resolution in DPI