Skip to content

Music with Python (and a musical instrument)

I wrote a blogpost earlier on harnessing musical grooves with code, and at the end of one fine unproductive day in an epiphanic kill-yourself moment, decided that I’d start off and give it a try.  An hour of python hacking later, the result was quite pleasing.

Making sound is pretty easy, but what distinguishes music is the structure and the scales. That’s the consensus, but there’s also the possibility that human ears might just be used to what we called Music today, which is probably why we’re used to songs in 4/4 time signatures and we like the Beatles. Make no mistake, I love the Beatles. Decades of listening to otherwordly cacophony in, say, 25/16, might probably make one a magnificent weirdo.

Ok, so I decided to start off with a note-generator in 4/4 time. Here’s the code.

  • First, the basic note-generator. Generates a sine wave of user-specified frequency freq, volume vol and duration dur, and appends the sound to a file with a filename name. I use the extension .au, but .wav is fine too. Anything else isn’t.
from struct import pack
from math import sin, pi
import time
from populate import _listen_

def _play_(name, freq, dur, vol, mode='ab'):
    """ Generate sound with frequency freq, duration dur, and volume vol """
    _dump_ = open(name, mode)
    _dump_.write('.snd' + pack('>5L', 24, 8*dur, 2, 8000, 1))
    _factor_ = 2 * pi * freq/8000
    for count in range(8 * dur):
        _wave_ = sin(count * _factor_)
        _dump_.write(pack('b', vol * 64 * _wave_))
    _dump_.close()

if __name__=="__main__":
_play_("foo.au", 50, 1000, 1, 'ab')


view raw sound.py This Gist is brought to you using Simple Gist Embed.
  • Next, the Scales. Two dictionaries, _freq_ and _midi_, which are populated with note-frequency key-value pairs using the _listen_ function. From this table, A0 has a frequency value of 27.50, and the ascending notes are just part of a geometric progression with a common ratio 1.059463094. So we start off with A0 (Lower notes like C0 have very low frequencies and are barely heard. The discernibility starts at around A0.) and assign note symbols with respective frequencies. When _listen_ is run, the two dicts are populated.
_freq_={}
_midi_={}

def _listen_(_firstNoteInRange_, _lastNoteInRange_, _noteInterval_, _midiCounter_):
    """ Fills dictionaries with note symbols and corresponding frequency values """
    notes = ['A0', 'A#0', 'B0', 'C1', 'C#1', 'D1', 'D#1', 'E1', 'F1', 'F#1', 'G1', 'G#1', 'A1', 'A#1', 'B1', 'C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2', 'A2', 'A#2', 'B2', 'C3', 'C#3', 'D3', 'D#3', 'E3', 'F3', 'F#3', 'G3', 'G#3', 'A3', 'A#3', 'B3', 'C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4', 'A4', 'A#4', 'B4', 'C5', 'C#5', 'D5', 'D#5', 'E5', 'F5', 'F#5', 'G5', 'G#5', 'A5', 'A#5', 'B5', 'C6', 'C#6', 'D6', 'D#6', 'E6', 'F6', 'F#6', 'G6', 'G#6', 'A6', 'A#6', 'B6', 'C7', 'C#7', 'D7', 'D#7', 'E7', 'F7', 'F#7', 'G7', 'G#7', 'A7', 'A#7', 'B7', 'C8', 'C#8', 'D8', 'D#8']

    _bwdf_ = 0
    while _firstNoteInRange_ <= _lastNoteInRange_:
        _freq_[notes[_bwdf_]] = _firstNoteInRange_
        _midi_[notes[_bwdf_]] = _midiCounter_
        _firstNoteInRange_ *= _noteInterval_
        _firstNoteInRange_ = round(_firstNoteInRange_, 4)
        _bwdf_ += 1
        _midiCounter_ += 1

if __name__=="__main__":
_listen_(27.5, 5000, 1.059463094, 21)

view raw populate.py This Gist is brought to you using Simple Gist Embed.
  • So now the notes are ready to be thrown in together in a structure. 4/4 time, hence 4 _beats_, a randomly chosen 1-to-5 second _intervalLength_, which I decided not to use since I’m setting _interval_ to 0, so there will be no silence between the notes. So, one _barLength_ contains _beats_ number of _noteLength_s and _interval_s. Again, this is a bit redundant and for future improv.  I chose the C-major Arpeggio arbitrarily to test out the module.  To make different riffs every time, I randomized the selection of notes and appended them to an empty list, in the first loop. In the second loop, the innerloop churns out the 4/4 riff, adding a 0-second interval for a snappy effect during the transition from one note to another. The outerloop repeats the riff twice. Now the file is appended with the riff. Running this module n times appends n riffs to the foo.au file.
import populate
import sound
import random

populate._listen_(27.5, 5000, 1.059463094, 21)
_beats_ = 4
_intervalLength_ = random.choice(range(1,5))*1000
_interval_ = 0
_noteLength_ = random.choice([500,1000,2000,3000,4000,5000])
_barLength_ = _beats_ * (_intervalLength_ + _noteLength_)
_CmajorArpeggio_ = ['C3','E3','G3','B3']
_note_ = []


for base in range(1, _beats_+1):
_note_.append(random.choice(_CmajorArpeggio_))

for repeat in range(1,3):
for base in range(1, _beats_+1):
sound._play_("foo.au", populate._freq_[_note_[base-1]], _noteLength_, 1, 'ab')
sound._play_("foo.au", 0, _interval_, 1, 'ab')


view raw sound.py This Gist is brought to you using Simple Gist Embed.

Arpeggio in C Major runs through the first C, the third E and the fifth G. Adding the B was a fuckup, but it added a melancholy minor-key flavor, so I’m not grumbling.

The full code is here.

And here’s one such generated file, converted to mp3 since WordPress doesn’t allow .au files.

Disclaimer: I do not own responsibility for ear damage or nausea.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

That didn’t sound really pleasant, so I thought I’d go ahead and improvise on the generated C Major Arpeggio riff with my electric guitar.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

And then I got really greedy and added an acoustic touch.

Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here. You also need to have JavaScript enabled in your browser.

I plan to try out different patterns, styles, algorithms and time-signatures. Since this can be a never-ending venture, I’ve opened a new page here for Music. If you’re interested in collaborating, feel free to shoot me a mail.

Here’s a wanting list of TODOs:

TODOs:
Incorporate Karplus-Strong for plucked-string sound.
Try different algorithms.
Reduce randomizations.
Make it choose between different styles (rock, pop, reggae, swing etc), based on different time signatures.
Add a database of scales and corresponding notes.
Think of more TODOs.

/SignOff

Categories: Algorithms, Code, Music, Uncategorized.

Tags: , , , , , , , , ,

‘Build-up and Explode’ Rock

I’ve always liked songs that build-up and explode into awesomeness. It’s like piling a huge deck of cards and watching it fall apart. There can’t be a better reward after all that arrangement and building-up. Effect on the listener? Mind blown. Making a great build-up song is, IMO, the testament to a Rock band’s potential. Here’s my personal favorites-list of such songs(in no order).


Bohemian Rhapsody, Queen. Obvious entry. Operatic stuff ending in Hard Rock with an emotional outro. RIP Freddie.


Echoes, Pink Floyd. Spacey. Builds up into an explosion of more spaciness.


Stairway To Heaven, Led Zeppelin. Another obvious entry. Widely considered one of the greatest Rock songs ever. That’s the power of an epic build-up.


Starless, King Crimson. Robert Fripp, you own. Dark and chilling. The final dispelling is like apocalypse.


Exit Music (For a Film), Radiohead. Radiohead’s the kind of band that can take a couple of minor chords and make a really great, soothing melody out of it.


Paperhouse, Can. Japanese vocalist and German musicians on a grooveride. Complete brainfucking grooveride. The album, Tago Mago, is probably my all-time favorite. Every song is a build-up song, and the whole album builds up and bursts into tranquility, like a sunset.


Marquee Moon, Television. This one meanders all about and bursts into a beautiful outro. And then the meandering resumes, and you’re like ‘You sly bastards!’. Punk goodness.


The Herald, Comus. Folk awesomeness. One of the most haunting and beautiful songs I’ve heard. Female vocals, violins, flutes, Acoustic Guitar and something that sounds like a Theremin.


Soap Shop Rock, Amon Duul II. Kraut Psyche with Electric Guitars.


Supper’s Ready, Genesis. Peter Gabriel’s easily a genius. The vocals in the outro are breathtaking.


Free Bird, Lynyrd Skynyrd. Plain Good Classic Rock.


One, Metallica. Not a metal fan, but this has a kick-ass riff and is memorable.


A Day in the Life, The Beatles. One of the earliest build-up Rock songs. I’m not one to say that even cacophony sounds good on a Beatles record, but this is artistic.


November Rain, Guns N Roses. Another great classic hard rock song.


Tame, Pixies. When Black Francis starts whispering, you never know what’s coming.


I can safely say that these are some of the best songs Rock has to offer. Laters then.

Categories: Music, Uncategorized.

Tags: , , , ,

Dear Mr.Sibal

I’m a pseudo-human who took a stroll down Desi country. Freedom I felt, free air I smelt. There’s craploads of ‘em. There’s some, and then there’s some more. When you see that poor scruffy dog bathing in the roadside gutter, you know you’re in free country. When you see that silly, discordant traffic, you know you’re in free country. When you see small poor kids running behind mobile icecream stalls like they’d been galvanized, you know you’re in free country. And yet, there was a rift. There were free people, and then there were chained people. Chained by poverty, misery, illiteracy and damnation. My senses were assaulted, but I realized, I’d rather not be gagged.

There you go, sir. Work ahead and free them. When they smell the free air, they would be exhilarated enough to change the nation. A sudden burst of Oxygen gets you so high, you feel like reaching out for the clouds. Don’t gag the free people instead.

Open up your mind just a little bit. Y’know, just that teeny-tiny bit through which some light can stream in and fuel your thought.

Cheerio, have a thoughtful day.

Categories: Introspection, Politics, Rants.

Tags: , , , ,

The Analogy to Life, the Universe and Everything

Sometime in the past, a friend asked me: ‘Why do you program?’. I told her: ‘Cos I love to?’. Cliche. And then I grew, and the reason-stack grew, and the love-it response was pushed somewhere towards the top, belonging with other items like:

  • I’m passionate about it.
  • I wanna become a software developer.
  • [scarcely-thought-out reason associated with adapting to global trends]

Traversing down to the middle of the stack, there were items like It’s Art and It’s mindblowing what you can do with just a computer, at the comfort of your home.

reason-stack
Hit Rock Bottom-


Groove

Code is Groovy. Not the dandy-groovy thing. It has these grooves, like a screw does. Like a screw, it fits in. Somewhere deep down in the cerebral chasms. Which is, in all likelihood, the same Modus Operandi of Music and Math. It’s almost like fitting these grooves into threaded holes in the brain. The brain functions on algorithms and patterns, and everything it coughs up is patterned in some way or the other. Nothing else can explain why most people sound their vehicle horns like ‘Beep Beeeep’, or rev up their engines with ‘Vroom Vroooom’. That’s a geometric progression of two elements with a common ratio of 2. Yet, it happens so subtly, unnoticed, everyday, everywhere, all the friggin’ time. It’s a daily street-dose of math, music, and it also gives us a code analogy. A codalogy, if I may.

#python-like
for i in [1,2]:
     honk(delay=i)
     sleep(ShortestDelayBetweenReleasingHornAndPressingAgain)

Pizza!

equal sectors

Another one of these commonplace applications of patterns and math is what enhances the droolworthiness of a pizza. The whole structure is progressively bisected to about 8 pieces. This is the mainstream way of cutting a pizza, and apart from giving equal pieces, it also makes the pizza look the most sexy. A different pattern, like closely placed vertical segments probably won’t look great. Here’s a codalogy for how most pizzas in the world are cut(again, a geometric progression with common ratio 1/2):

#python-like
for i in range(1,numberOfPieces):
     for each piece on the table:
          cutPieceInHalf()

There are an infinite other ways to split a pizza into equal parts, but this is probably the simplest, most structured, and beautiful way of cutting it, and that makes it mainstream. Also, note the reusability. The code above doesn’t just apply to a pizza. Map it to microcontroller language, write the function code, interface hardware, and you can have a cutter that emulates this pattern for just about any structure.

There are inherent grooves and patterns down below in the depths of the brain, which are mapped to the outer physical world. This mapping is spontaneous and natural. Go dance or headbang to a groovy beat, or find yourself unconsciously drumming with your fingers or nodding your head off to distant music, and the mapping becomes conspicuous. Code exploits these patterns and grooves. There’s no pattern you can’t reproduce in code. Which leads us to-


Hardware enslavement

It’s very tempting to write a loo joke, so here goes a codalogy:

#python-like
while True:
      if(stomach.isEmpty()==True):
            feed()
#python-like
while True:
      if(bowels.soundShitAlarm()==True):
            dashToTheCrapper()

Let’s suppose the former loop were to fail due to some unknown reason or the conspiracy of the devil. We’d stuff ourselves and explode. And if the latter fails? Again, we’d stuff ourselves and explode. And the world would be a shitbath. And……………..!force stop.

Failure of a trivial-looking piece of code can spell worldly doom. Things at present are the way they are, because these cerebral loops work the way they do. (Ref. Godel Escher Bach)

This is no different from Assembly programming or, say, Arduino projects. Using the microcontroller to interface with hardware sounds like a perfect analogy to biological or cognitive processes. An example code for making a Piezo-Electric buzzer buzz out the automobile ‘Beep Beeeep’ might look this way:

int noteDurations[] = {
  durationOfTheFirstHonk,durationOfTheFirstHonk*2 };

void setup() {
  for (int thisNote = 0; thisNote < 2; thisNote++) {
    int noteDuration = 1000/noteDurations[thisNote];
    tone(somePin, frequencyOfVehicleHorn,noteDuration);
    delay(ShortestDelayBetweenReleasingHornAndPressingAgain);
    noTone(somePin);
  }
}

Code can mimic natural symmetry. Program separate hardware parts for a cumulative goal(a sense-response system which senses the surrounding environment for input of specific type, and a corresponding preset response), interface them through a microcontroller, join them all together in one body structure, and there's a Robot. The analogy is striking. Code is the universal analogy.


Going against the groove

Like everything else, there are certain grooves that don't wedge into certain threads. Forcing the brain to faithfully construct an asymmetrical pattern can be a pain in the assbrain.

A small game that would show this would be - 'I'll ask you questions, and you keep answering to the previous question.' To complicate it further, the answers could be for questions 2 or 3 displaced from the present. Yeah Right. Give the brain a groove, and ask it to form an anti-groove of sorts. This is like walking in the opposite direction and increasing the distance to the goal. Here, of course, the brain stutters unless it chooses not to acknowledge the main pattern and instead, create the required pattern from memory, in a dedicated process.

Also, random number generation. Try going into a coughing-up-random-numbers-spree. You'll notice that a few adjacent numbers are innocently close, or desperately far away depending on the scale. The uneasiness of the brain to breach patterns is again obvious here.

Random number generation in computers isn't really random, in the true sense of the word. It either depends on a seemingly random external physical event(like, say, results of rolling a dice, or the measure of radioactive decay) or a pseudo-random number generator(pseudo - pretending to be). Here's the classic pseudo-random number generator from K&R:

unsigned long int next = 1;
/* rand: return pseudo-random integer on 0..32767 */
int rand(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}
/* srand: set seed for rand() */
void srand(unsigned int seed)
{
next = seed;
}

Here's xkcd's take.
xkcd random number generator

The brain adheres to patterns that are fed to it. An artificial sense-response system, need not, necessarily. Like in an answering bot that keeps appending the present question to a linked list, and keeps answering the question from the penultimate node. Code can harness anti-grooves. It can go against the groove.


The Code Legacy

The universality of code makes it live on a world of its own. It can aid in mapping almost any system into any other system. That gives humans a lot of domains to work on. On a world of its own, some domains-

  • Civil Engineering - Software construction, Web design, Application development, and an infinite other things.
  • Artistry - Algorithmic music composition - like fractal music, algorithmic and representational art and an infinite other things.
  • Science - Artificial Intelligence, Machine Learning, Neural Networks and an infinite other things.
  • Electronics - Microcontrollers, Hardware design and an infinite other things.
  • Finance - High-Frequency Trading algorithms, Stock predictors and an infinite other things.
  • And an infinite other things.


Without code, most technology wouldn't exist. We breathe and live and bathe and eat on code. More importantly on a mainstream scale, we Facebook on code.


/MusicalSignOff

All this stuff about indiscernible and difficult music, it's all in the grooves. The more complex it is, the more time it takes to sink into the brainpits.

Here's a quite inaccessible but genius 70s Kraut groove:

[Link]

And a simpler Tamil Kuthu(translates to punch, but I call it orgasmic percussion). Note: Simple, awesome, trending groove viral on the interwebs as of the time of this post. No wonder it hit mainstream. Everyone just groov'd. Notice the people in the video mapping their cerebral grooves to headnods. Or maybe you're doing it yourself.

[Link]

Grooves and patterns are what make pleasant music pleasant, great artwork great, and a hot chick hot, even. And in all likelihood, AI has everything to do with grooves fitting into threads. An explosion of patterns and structure and symmetry. If in future a machine passes the Turing test, it would probably attribute to its skillful perception of grooves and patterns and structure. There are deeper mysteries down in the mind than in the universe. If humans ever find the Answer to Life, the Universe and Everything, it would be because of code. Nothing exploits these structures better than code. Simply because Code is the Analogy to Life, the Universe and Everything.

I wanted to dump more thoughts in, but, of course, time-constraints and insecurity always beat you. Hopefully I'll follow up on these in further blog posts.

Going back to the top of the reason-stack now, 'Why do you program?'. 'Cos I love to!'

Gotta love teh code, mahn.

/SignOff

Categories: Algorithms, Code, Introspection, Music.

Tags: , , , , , , ,

Moov’d

Moved to own domain at last. Hello world!

Categories: Uncategorized.