Introduction to Digital Music with Python Programming: Learning Music with Code 1st Edition Horn instant download
Introduction to Digital Music with Python Programming: Learning Music with Code 1st Edition Horn instant download
https://ebookmeta.com/product/introduction-to-digital-music-with-
python-programming-learning-music-with-code-1st-edition-horn/
https://ebookmeta.com/product/introduction-to-digital-music-with-
python-programming-learning-music-with-code-1st-edition-michael-
horn/
https://ebookmeta.com/product/an-introduction-to-statistical-
learning-with-applications-in-python-gareth-james/
https://ebookmeta.com/product/an-introduction-to-programming-and-
computer-science-with-python-first-edition-clayton-cafiero/
https://ebookmeta.com/product/seduced-by-days-1st-edition-milly-
taiden/
https://ebookmeta.com/product/writing-by-choice-3rd-edition-eric-
henderson/
https://ebookmeta.com/product/further-advances-in-internet-of-
things-in-biomedical-and-cyber-physical-systems-193-intelligent-
systems-reference-library-193-valentina-e-balas-editor/
https://ebookmeta.com/product/mcgraw-hill-education-ccrn-
review-1st-edition-michael-reid/
https://ebookmeta.com/product/dns-security-for-dummies-infoblox-
special-edition-joshua-m-kuo-robert-nagy-cricket-liu/
Natural Resources S. V. Ciriacy-Wantrup (Editor)
https://ebookmeta.com/product/natural-resources-s-v-ciriacy-
wantrup-editor/
Introduction to Digital Music
with Python Programming
DOI: 10.4324/9781003033240
Typeset in Bembo
by codeMantra
Melanie dedicates her contribution of the book to the
memory of her friend, Bernie Worrell, who taught her
how to listen.
Mike dedicates his contribution to his wife, Diana Reed,
and his children, Madeleine and Lucas.
Contents
List of fgures ix
Photo and illustration credits xiii
Foreword xiv
Acknowledgments xvi
Michael Horn
Chicago, Illinois ( July 2021)
Note
1 I was also fortunate to have grown up in a time and place where these ac-
tivities were seen as socially acceptable for a person of my background and
identity.
Acknowledgments
We are grateful to the many people who have helped make this book possi-
ble. We especially want to thank Dr. Amartya Banerjee who has anchored
the TunePad development team. The TunePad project grew out of a col-
laboration with the EarSketch team at Georgia Tech that was initiated by
Dr. Brian Magerko and Dr. Jason Freeman. We thank Dr. Nichole Pinkard,
Dr. Amy Pratt, and the Northwestern Ofce of Community Education
Partnerships. We thank the TIDAL Lab team at Northwestern University
including Mmachi Obiorah, Wade Berger, Izaiah Wallace, Brian Andrus,
Jamie Gorrson, Matthew Brucker, Lexie Zhao, Ayse Hunt, Kallayah
Henderson, Cortez Watson Jr., Sachin Srivastava, and many, many oth-
ers. We thank our community partners including the Evanston Public
Library, the NAACP of DuPage County, the James R. Jordan Foun-
dation, the Meta Media program at the McGaw YMCA, the Hip-Hop
FIRM, EvanSTEM, the Center for Creative Entrepreneurship, Studio
2112, the James R. Jordan Boys and Girls Club, Lake View High School
and Marshaun Brooks, Lane Tech High School and Amy Wozniak, Gary
Comer Youth Centers, and Chicago Youth Centers, Project Exploration,
BBF Family Services, and the Museum of Science and Industry. Shout-
outs to Marcus Prince and Sam Carroll who gave us insightful curriculum
ideas, to Tom Knapp who contributed to TunePad’s graphical design, and
to the amazing interns we’ve worried with over the years.
Special thanks go to the people who gave input into the ideas and text
of this manuscript including George Papajohn and Diana Reed. We also
thank Joseph Mahanes, Abbie Reeves, and others who put up with us
while we worked on this book.
TunePad was created by the Tangible Interaction Design and Learn-
ing (TIDAL) Lab at Northwestern University in collaboration with the
EarSketch team at the Georgia Institute of Technology and with fund-
ing from the National Science Foundation (grants DRL-1612619, DRL-
1451762, and DRL-1837661) and the Verizon Foundation. Any opinions,
fndings, and/or recommendations expressed in the material are those of
the authors and do not necessarily refect the views of the funders.
1 Why music and coding?
These eight lines of Python code tell TunePad to play a pattern of kick
drums, snare drums, and high-hats. Most of the lines are playNote in-
structions, and, as you might have guessed, those instructions tell TunePad
to play musical sounds indicated by the numbers inside of the parentheses.
This example also includes something called a loop on line 6. Don’t worry
too much about the details yet, but the loop is an easy way to repeat a set
of actions over and over again. In this case, the loop tells Python to repeat
lines 7 and 8 four times in a row. The screenshot (Figure 1.1) shows what
this looks like in TunePad. You can try out the example for yourself with
this link: https://tunepad.com/examples/roses.
connection, and a small budget. The reasons behind the shift to digital
production tools are obvious. Computers have gotten to a point where
they are cheap enough, fast enough, and capacious enough to do real-time
audio editing. We can convert sound waves into editable digital informa-
tion with microsecond precision and then hear the efects of our changes
in real time. These DAWs didn’t just appear out of nowhere. They were
constructed by huge teams of software engineers writing code—millions
of lines of it. As an example, TunePad was created with over 1.5 million
lines of code written in over a dozen computer languages such as Python,
HTML, JavaScript, CSS, and Dart. Regardless of how you feel about the
digital nature of modern music, it’s not going away. Learning to code will
6 Why music and coding?
help you understand a little more about how all of this works under the
hood. More to the point, it’s increasingly common for producers to write
their own code to manipulate sound. For example, in Logic, you can write
JavaScript code to process incoming MIDI (Musical Instrument Digital
Interface) data to do things like create custom arpeggiators. Learning to
code can give you more control and help expand your creative potential
(Figure 1.2).
1 for _ in range(16):
2 if randint(6) > 1: # roll the die for a random number
3 playNote(4, beats=0.5) # play an eighth note
4 else:
5 playNote(4, beats=0.25) # or play 16th notes
6 playNote(4, beats=0.25)
What’s cool about these efects is that they’re parameterized. Because the
code describes the algorithms to generate music, and not the music itself, it
means we can create infnite variation by adjusting the numbers involved.
For example, in the trap hi-hat code, we can easily play around with how
frequently stuttered hats are inserted into the pattern by increasing or de-
creasing one number. You can think of code as something like a power drill;
you can swap out diferent bits to make holes of diferent sizes. The drill bits
are like parameters that change what the tool does in each specifc instance.
In the same way, algorithms are vastly more general-purpose tools that can
accomplish myriad tasks by changing the input parameters.
Creating a snare drum riser with code is obviously a very diferent kind
of thing than picking up two drumsticks and banging out a pattern on
a real drum. And, to be clear, we’re not advocating for code to replace
learning how to perform with live musical instruments. But, code can be
another tool in your musical repertoire for generating repetitive patterns,
exploring mathematical ideas, or playing sequences that are too fast or
intricate to play by hand.
1.6.3 REASON 3: Code lets you build your own musical toolkit
Becoming a professional in any feld is about developing expertise with
tools—acquiring equipment and knowing how to use it. Clearly, this
is true in the music industry, but it’s also true in software. Professional
software engineers acquire specialized equipment and software packages.
They develop expertise in a range of programming languages and techni-
cal frameworks. But, they also build their own specialized tools that they
use across projects. In this book, we’ll show you how to build up your own
8 Why music and coding?
library of Python functions. You can think of functions as specialized tools
that you create to perform diferent musical tasks. In addition to the exam-
ples we described above, you might write a function to generate a chord
progression or play an arpeggio, and you can use functions again and again
across many musical projects.
1.6.4 REASON 4: Code is useful for a thousand and one other things
As we mentioned earlier in this chapter, Python is one of the most power-
ful, multi-purpose languages in the world. It’s used to create web servers
and social media platforms as much as video games, animation, and music.
It’s used for research and data science, politics and journalism. Knowing a
little Python gives you access to powerful machine learning and artifcial
intelligence (AI/ML) techniques that are poised to transform most aspects
of human work, including in creative domains such as music. Python is
both a scripting language and a software engineering platform—equal
parts duct tape and table saw—and it’s capable of everything from quick
fxes to durable software applications. Learning a little Python won’t make
you a software engineer, just like learning a few guitar chords won’t make
you a performance musician. But it’s a start down a path. An open door
that was previously closed, and a new way of using your mind and a new
way of thinking about music.
Sometimes we’ll write code in a table with line numbers so that we can re-
fer to specifc lines. When we introduce new terms, we’ll bold the word.
If you get confused by any of the programming or music terminology,
check out the appendices, which contain quick overviews of all of the
important concepts. We’ll often invite you to follow along with online
examples. The best way to learn is by doing it yourself, so we strongly
Why music and coding? 11
encourage you to try coding in Python online as you go through the
chapters.
Notes
1 It’s said that fans were so infatuated with Liszt’s piano “rockstar” status that
they fought over his silk handkerchiefs and velvet gloves at his performances.
2 We recommend https://www.w3schools.com/python/.
Interlude 1
BASIC POP BEAT
In this interlude we’re going to get familiar with the TunePad interface by
creating a basic rock beat in the style of songs like Roses by SAINt JHN.
You can follow along online by visiting
https://tunepad.com/interlude/pop-beat
DOI: 10.4324/9781003033240-2
Basic pop beat 13
When you’re done, your project should look something like Figure 1.5.
Go ahead and press the Play button at the top left to hear how this
sounds. Congratulations! You’ve just written a Python program.
Syntax errors
Occasionally your code won’t work right and you’ll get a red error mes-
sage box that looks something like Figure 1.6. This kind of error message
is called a “syntax” error. In this case, the code was written as playnote
with a lowercase “n” instead of an uppercase “N”. You can fx this error
by changing the code to read playNote (with an uppercase “N”) on line
2 (Figure 1.6).
Basic pop beat 15
You might start to notice the text that comes after the hashtag symbol (#)
is a special part of your program. This text is called a comment, and it’s for
human coders to help organize and document their code. Anything that
comes after the hashtag on a line is ignored by Python. Try playing this
snare drum cell to hear how it sounds. You can also play the kick drum
cell at the same time to see how they sound together.
STEP 5: Hi-hats
Click on the ADD CELL button again to add a third drum cell. Change
the title of this cell to be “Hats” and add the following code:
Note
1 We recommend using the free Google Chrome browser for the best overall
experience.
2 Rhythm and tempo
Rock 100–140
R&B 60–80
Pop 100–132
Reggae 60–92
Hip-hop 60–110
Dubstep 130–144
Techno 120–140
Salsa 140–250
Bachata 120–140
You can adjust the tempo of your metronome with the bpm indicator
(Figure 2.1). As this example illustrates, computers excel at keeping a per-
fectly steady tempo. This is great if you want precision, but there’s also a
risk that the resulting music will sound too rigid and machine-like. When
real people play music they often speed up or slow down, either for dra-
matic efect or just as a result of being a human. Depending on the genre,
performers might add slight variations in rhythm called swing or shufe,
Figure 2.1 TunePad project information bar. You can click on the tempo, time
signature, or key to change the settings for your project.
20 Rhythm and tempo
that’s a kind of back and forth rocking of the beat that you can feel almost
more than you can hear. We’ll show you how to add a more human feel to
computer generated music later in the book.
Figure 2.5 Common note symbols starting with a whole note (four beats) on the
top down to 16th notes on the bottom. The notes on each new row are
half the length of the row above.
Standard notation also includes dotted notes, where a small dot follows the
note symbol. With a dotted note, you take the original note’s duration
and add half of its value to it. So, a dotted quarter note is 1.5 beats long, a
dotted half note is 3 beats long, and so on.
There are also symbols representing diferent durations of silence or
“rests”.
Three-Four Time
There are 3 beats in each measure, and the quarter
note gets the beat.
Three-Eight Time
There are 3 beats in each measure, and the eighth
note gets the beat.
The most common time signature is 4/4. It’s so common, in fact, that
it’s referred to as common time. It’s often denoted by a C symbol shown
in the table above. In common time, there are four beats to each measure,
and the quarter note “gets the beat” meaning that one beat is the same as
one quarter note.
Vertical lines separate the measures in standard notation. In the example
below, there are two measures in 4/4 time (four beats in each measure, and
each beat is a quarter note).
If you have a time signature of 3/4, then there are three beats per measure,
and each beat’s duration is a quarter note. Some examples of songs in 3/4
time are My Favorite Things from The Sound of Music, My 1st Song by Jay Z,
Manic Depression by Jimi Hendrix, and Kiss from a Rose by Seal.
26 Rhythm and tempo
If those notes were eighth notes, it would look like this:
Other common time signatures include 2/4 time (with two quarter note
beats per measure) and 2/2 time (with two half note beats in each measure).
With 2/2 there are actually four quarter notes in each measure because
one half note has the same duration as two quarter notes. For this reason,
2/2 time is performed similarly to common time, but is generally faster.
It is referred to as cut time and is denoted by a C symbol with a line
through it (see table above).
You can adjust the time signature of your TunePad project by clicking
on the time indicator in the top bar (see Figure 2.1).
Kick or bass The kick drum (or bass drum) makes a loud, low 0 and 1
drum thumping sound. Kicks are commonly placed on
beats 1 and 3 in rock, pop, house, and electronic
dance music. In other genres like hip-hop and funk,
kick drums are very prominent, but their placement
is more varied.
Snare Snare drums make a recognizable sharp staccato 2 and 3
sound that cuts across the frequency spectrum. They
are built with special wires called snares that give
the drum its unique snapping sound. Snare drums
are commonly used on beats 2 and 4.
Hi-hat The hi-hat is a combination of two cymbals 4 (closed)
sandwiched together on a metal rod. A foot pedal 5 (open)
opens or closes the cymbals together. In the closed
position the hi-hat makes a bright tapping sound. In
the open position the cymbal is allowed to ring out.
Hi-hats have become an integral part of rhythm
across almost all genres of popular music.
Low, mid, Tom drums (tom-toms) are cylindrical drums that 6, 7, 8
high tom have a less snappy sound than the snare drum. Drum
kits typically have multiple tom drums with slightly
different pitches (such as low, mid, and high).
Crash A large cymbal that makes a loud crash sound, often 9
cymbal used as a percussion accent.
Claps and Different TunePad drum kits include a range of 10 and 11
shakers other percussion sounds common in popular music
including various claps, shakers, and other sounds.
you can choose from several diferent drum kits including an 808 and rock
kits. You can change the instrument by clicking on the selector shown
below (Figure 2.8).
TO J. D. HOOKER.
Dr. Gray wrote a notice of Charles Wright for the “American Journal of
Science,” in which he says that “Charles Wright was born at Wethersfield,
Connecticut; graduated at Yale in 1835. Had an early love for botany, which
may have taken him to the South as a teacher in Mississippi, whence he
went to Texas, joining the early immigration, and occupied himself
botanizing and surveying, and then again in teaching. He accompanied
various expeditions, and no name is more largely commemorated in the
botany of Texas, New Mexico, and Arizona than Charles Wright. It is an
acanthaceous genus of this district, of his own discovery, that bears the
name of Carlowrightia. Surely no botanist ever better earned such scientific
remembrance by entire devotion, acute observation, severe exertion, and
perseverance under hardship and privation.” He was engaged later for
several years “in his prolific exploration of Cuba.”
“Mr. Wright was a person of low stature and well-knit frame, hardy
rather than strong, scrupulously temperate, a man of simple ways, always
modest and unpretending, but direct and downright in expression, most
amiable, trusty, and religious. He accomplished a great amount of useful
and excellent work for botany in the pure and simple love of it; and his
memory is held in honorable and grateful remembrance by his surviving
associates.”[135]
TO JOHN H. REDFIELD.
TO S. M. J.
TO W. M. CANBY.
Cambridge,
November 19, 1885.
My dear Canby,—Many thanks for your felicitations. There is much I
want to write, and to say what a surprise we had, and how perfect the vase
is. But my arm is worn out with note-writing.
Yours affectionately,
Asa Gray.
Two poems and a poetical epigram came among the rest!
Cambridge,
January 31, 1886.
My dear Friend,—I am a laggard correspondent, I fear. Here are your two
most friendly and interesting letters, as far back as November, one of which
crossed, and one which announced, the reception of my long letter which
gave a sketch of our journeyings which began almost a year ago. For we are
now already in the middle of another winter. I doubt if we shall flee from
this one, although it has shown some severity. In the first place, we may
thankfully say that neither Mrs. Gray nor I can say that we require it; and I
cannot bear to lose the time: I seem to need the more of this as the stock
diminishes; for, somehow, I cannot get as much done in a day as I used to
do. Moreover, it is no good running away from winter unless you can go
far. For our southern borders have been unusually wintry, and they want our
guards and preparations against cold.... We were glad enough to get back to
our well and equably warmed house, where, indeed, we are most
comfortable.
You called my attention, I believe, to Professor Allen’s book on the
“Development of Christian Doctrine.” I take shame to myself that I did not
procure and read it. But I know its lines, and read some part of it before it
was in the book, and, of course, I like it much.
I am going, in a few days, to send you a little book, with similar
bearings, which I read in the articles of which it is made up. I think you will
find much of it interesting.
Bishop Temple’s “Bampton Lectures” seemed to me very good as far as
it went, but hardly came up to expectation.
I saw something of Canon Farrar when here. He pleased well, and I think
was well pleased; and personally he was very pleasing and lovable.
I wish more of the English Churchmen would visit us, and give more
time especially to the study of their own branch of the church in the United
States,—a very thriving one. I think they might learn much that would be
helpful and hopeful,—difficult as it may be to apply the experience and the
ways of one country to another.
I have seen, but not read, Mr. Forbes’s “Travels in Eastern Archipelago.”
Those who have read it here say it is very interesting. We have a great lot of
his dried plants from Sumatra and Java, unnamed, which at odd hours I am
arranging for the herbarium. I hope that in his new journey he will manage
to make better specimens. But, as he is primarily an entomologist, this can
hardly be expected. But, if I rightly understand, he goes out now with a
good backing and probably better conveniences for collecting than he could
have had before.
We have been, and still are, much interested in English politics and
election excitements. You are having very anxious times, indeed. What a
pity that some one party, that is, one of the two great parties, is not strong
enough, and homogeneous enough, to command the situation for the time
being, and to deal independently of Parnell, or, indeed, of Chamberlain....
We Americans are wonderfully peaceful—our only real questions now
pending are financial, and those not yet treated as they ought to be, on party
lines. We have an awful silver craze; but we hope to arrest it before it comes
to the worst, though sense and argument are at present ineffectual.
We have a comfortable trust in the principle that “Providence specially
protects from harm the drunken, the crazy, and the United States of
America.”
I see our friend Professor Thayer now and then. He is well and
flourishing. Mrs. Gray and I are very well indeed, and we send our most
cordial good wishes to you all.
Very sincerely yours,
Asa Gray.
TO J. D. HOOKER.
TO A. DE CANDOLLE.
TO J. D. DANA.
TO J. D. HOOKER.
It was during this visit that Dr. Gray, when the family gathered one
morning for breakfast, had disappeared. He came in smiling when the meal
was half over, and in answer to the anxious question where he had been,
said, “Oh, I have been to say to Mrs. Rogers that I forgave her for getting
above me in the spelling-class.”
Cambridge, October 31, 1886.
Dear Hooker,—Thanks for a nice long letter from Bournemouth,
September 27. Thanks, too, for the hope—though rather dim—that you and
wife may come over to us in the spring. Before winter is over we must
arrange some programme; for we four must meet again somehow and
somewhere, while in the land of the living. But how is a problem.
... I see how difficult it must be for you to get away as far as to us. Our
obstacle to any amount of strolling away is mainly the fear that if I interrupt
my steady work on the “Flora of North America,” I may not get back to it
again, or have the present zeal and ability for prosecuting it.
On the other hand, if I and my wife do not get some playdays now, while
we can enjoy them, the time will soon come when we shall have to say that
we have no pleasure in them. Therefore we are in sore straits.... If really you
cannot come, then we will brave out the winter here, as we did last winter
and are none the worse; then we will seriously consider whether Mahomet
shall go to the mountain, which will not come to Mahomet.
I grind away at “Flora,” but, like the mills of the gods, I grind slowly, as
becomes my age,—moreover, to continue the likeness, I grind too
“exceedingly fine,” being too finical for speed, pottering over so many
things that need looking into, and which I have not the discretion to let
alone. Consequently the grist of each day’s work is pitiably small in
proportion to the labor expended on it. I am now at Malvaceæ, which I once
enjoyed setting to rights, and of which the North American species have got
badly muddled since I had to do with them.
If Sereno Watson—who should be back again in twenty days—will only
go on with the Cruciferæ, which he has meddled with a deal, and then do
the Caryophyllaceæ, which are in like case, we may by March 1st have all
done up to the Leguminosæ.
We learn to-day, through a pamphlet sent by Miss Horner, that Bunbury
is dead—in June last....
Your “Primer”—new edition—has not come yet. Do not forget it. And
then, as my manner is, I will see if I can find fault with it. Same with
Bentham’s “Hand-book,” new edition....
I do not wonder that you are happy and contented. We should so like to
see father, mother, and children in their encampment at Sunningdale. May
plenty of sunshine be theirs!
Ball has sent me early sheets of his book. I must find time to go through
its pages.
The L.’s abroad, except the two girls (who are to winter at San Remo)
are now en voyage homeward. William, their father, has been painted by
Holl. He is a good subject. Saw your sister B. (and kind Lombe); she writes
a charming letter to my wife; seems to hold her own wonderfully.
Cambridge, November 22, 1886.
Well, I have got safely through my seventy-sixth birthday, which gives a
sort of assurance. I have always observed that if I live to November 18, I
live the year round!
You are working at Euphorbs, etc.; I at Malvaceæ, in which I find a good
deal to do for the species, and something for the betterment of genera....
TO J. D. HOOKER.
TO A. DE CANDOLLE.
TO ——.
May 15, 1887.
I think the journey from Bâle, in Switzerland, to Salzburg was
wonderfully fine and a great success, and that May is a good time to do it,
while there is plenty of snow in the mountains. Lake Wallenstadt showed to
great advantage. And I had no idea that the pass of the Arlberg, from
Feldkirk to Innspruck, was so high or so very fine. I believe it is the highest
railway pass across the Alps. I was quite unprepared (which was all the
better) for the exquisite and wild, and in parts grand, scenery of the next
day’s journey through the heart of Lower Tyrol and the Salzburg
Salzkammergut, by a slower train, a roundabout road making more than
twice the direct distance from Innspruck to Salzburg, through the Zillerthal
and over a fairly high pass on to the upper part of the Salzach, and down it
through some wild cañons into the plain, from nine A.M. till five, of choicest
scenery. The great castle, so picturesquely placed in the Lichtenstein
(plain), is Schloss-Werden. Rainy day at Salzburg, or should have had noble
views. If the weather had been good, I think we would have driven from
Salzburg to Ischl, and then come by the Traunsee to Linz. But after all, from
my remembrance, it would hardly have come up to what we had already
seen. And though it was a rainy day for the Danube, we did see everything
pretty well, and most comfortably, in the ladies’ cabin of the steamer, with
windows all round the three sides, and most of the time the whole to
ourselves, or with only one quiet lady, who evidently cared nothing for the
views. J. says I was bobbing all the time from one side to the other. I was
looking out for the views which I had when going up the Danube forty-
eight years ago. J. thinks it not equal to the Rhine, but there is rather more
of it, or scattered over more space.
TO SIR J. D. HOOKER.