## Adding music notation to LaTeX with LilyPond

Posted: 27th December 2011 by Tim in LaTeX, LilyPond
Tags: , , , , , , , , , , ,

Ever wanted to add some music to a document? It’s not really a big feature for most word processors and most solutions involve creating an image using some third party software and copying that image into the document. The idea is the same in LaTeX, but it’s much easier to manage.

LilyPond is a free software package that allows you to create musical notation in a very flexible format. It can do music for piano, guitar (tabs and chords), drums, vocals… the list goes on. And better still, it can integrate with LaTeX quite easily with the lilypond-book program. Essentially, you add your lilypond code to your LaTeX document inline and run the document through the program to generate the images and add the various code to use those images. This spits out a .tex file which you can use to create your document. Sounds easy. And it is.

Let’s look at an example. I find it easiest to write my document using a .lytex extension; this allows lilypond to create a .tex file with the same name. If your file has a .tex then you have to mess around with output directories and such. If you’re using Vim and want to keep your TeX syntax highlighting working, I’ve described how to do that here.

Your file could look something like this:

mary.lytex
\documentclass{article} \begin{document}     An easy song to learn on the piano is Mary Had a Little Lamb:\\     \begin{lilypond}         \score { % start of musical score           <<             % beginning of musical staff. the \relative c' means that the             % notes are an octave higher than the default (ie: notes are             % notes are relative to middle c)             \new Staff \relative c' {                 e4 d c d e e e2 d4 d d2 e4 g g2                 e4 d c d e e e e d d e d c1             } % end of staff           >>         } % end of musical score     \end{lilypond} \end{document}

I’m not going to go through the LilyPond syntax, but basically the letters dictate the note and the numbers dictate the note length (4 means quarter note, 2 means half note, etc). Check out the website for a description of the full syntax.

So to create our document we run the following:

lilypond-book --format=latex --lily-output-dir=lilyfiles mary.lytex latex mary.tex

The first line will create mary.tex and the second will create the DVI document, which will look like this: