[Tex/LaTex] Writing musical pitches

macrosmusic

Is there a package or macro that allows me to easily typeset musical pitches, like the following:

enter image description here

? Indeed I would like to have subscripts for the octaves. Let's say

$\mathrm{E}\flat_3$

How would I write a macro producing this output, when the invocation is

\note{Eb3}

Like:

\newcommand{\note}[1]{???}

I would have to take the string apart, the first char goes into \mathrm, then there is an optional second char # or b, followed by a digit.

Best Answer

The only quirk is that you have to use brackets [] rather than braces {} to enclose the argument.

\documentclass{article}
\def\note[#1#2#3]{#1\if b#2$\flat_#3$\else\if#2##$\sharp_#3$\else$_#2$\fi\fi}
\begin{document}
\note[Eb3]
\note[A2]
\note[F#4]
\end{document}

enter image description here

If you would prefer the use of braces to brackets, then the following modification would do. It renames the \note from the above code as \xnote and creates a newcommand \note to do the argument translation.

\documentclass{article}
\newcommand\note[1]{\xnote[#1]}
\def\xnote[#1#2#3]{#1\if b#2$\flat_#3$\else\if#2##$\sharp_#3$\else$_#2$\fi\fi}
\begin{document}
\note{Eb3}
\note{A2}
\note{F#4}
\end{document}

Since egreg's answer seems to go beyond what the OP asked, providing reasonable behavior when either argument 2, argument 3, or arguments 2 and 3 are missing, I felt it incumbent to do the same (EDITED using Qrrbrrbr...brbrbrl's suggestion to enclose subscript definitions in braces, which will facilitate two-digit octave numbers, shown in last line of output):

\documentclass{article}
\newcommand\note[1]{\xnote#1\relax\relax\relax}
\def\xnote#1#2#3\relax{#1\if#2\relax\else\if b#2$\flat\if#3\relax%
  \else_{#3}\fi$\else\if###2$\sharp\if#3\relax\else_{#3}\fi$\else$_{#2}$\fi\fi\fi}
\begin{document}
\note{Eb3}
\note{A2}
\note{C#}
\note{A}
\note{Eb}
\note{F#4}

\note{F{14}}
\note{F#{14}}
\end{document}

enter image description here

Related Question