'Creating melodies programmatically
I'd like to play a little bit with making melodies programmatically.
I don't really care about the timbre, although if I could get it to sound like old-school 8-bit music that would be cool.
I would like to be able to play music by simply specifying for each note how long it is, when it is played (starting from the beginning of the song), and its pitch.
I want to use it in the following manner:
from awesomeMelodyLibrary import play
# Perhaps play accepts an iterable of 3-tuples where
# the items of the tuple are (pitch, duration_of_note, when_to_play)
# and then it would play those notes.
play([ (440, 200, 0), # A4
(440, 200, 200),
(660, 200, 400), # E5
(660, 200, 600),
(740, 200, 800), # F#5
(740, 200,1000),
(660, 400,1200) ])
And it would play the beginning of the alphabet song.
It does not have to be exactly that way, and I'd be fine with some limitations (e.g. be able to play up to only three notes at the same time) but the point is that I don't want to get dirty with raw sound data, handle details of mixing different sound clips in order to play chords, sound clips, etc.
Solution 1:[1]
Try RTcmix with the Python front-end.
It works best on OS X, though I use it on Ubuntu. It wasn't an easy build process, but you can see my post to their discussion list about my installation process on Ubuntu 12.04.
They have a variety of instruments available. One of my favorites is STRUM2, a plucked string instrument.
Here's how you would play a few notes in Python.
from rtcmix import *
rtsetparams(44100, 2)
load("STRUM2")
noteOnset = 0 #in seconds
duration = 1.0 # in seconds
amplitude = 10000
pitch = 440 # specified in hertz
squish = 1
decay = 1.0
pan = .5
STRUM2(noteOnset, duration, amplitude, pitch, squish, decay, pan)
It takes pitches in hertz by default, but this function can convert from MIDI key numbers to hertz.
def keynumToHertz(keynum):
lowestfreq = 8.175 #C-1
return lowestfreq * math.pow(2.0, float(keynum)/12.0)
If you want to specify the notes in standard notation ('Bb6', 'G#8', 'F-1', 'A4') then you could use the nameToNum function I wrote. Find it here.
Check out the documentation on their site for more complex examples, or my Github repo with implementations of several chapters of Notes from the Metalevel, a text on algorithmic composition. If you're interested in doing more than just playing hand-specified notes, I highly recommend a reading of that book. It's written for Lisp/Common Music, but my repo has the Python/RTcmix translations for a lot of it.
Solution 2:[2]
You can use the abjad or music21 libraries for python. There is a full description of the possible audio libraries in this website : Python in Music
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | messivanio |
| Solution 2 | juangocc |
