Tuesday, January 30, 2018

A Little Language for Music Composition | A Programmer's Approach to Song Construction

I was surprised by how successful I was at creating small animations, known as Poetic Computations and wanted to try the same thing with audio. Fortunately, much of the heavy lifting has already been done by the Web Audio API. The fact that I know nothing about music composition hardly seemed like a reason not to give this a try.

There are quite a few slick music APIs and creation tools out there, but I was curious if I could extend the lessons learned with my animation framework into the realm of music.

In the case of animations, my platform only allows for the creation of line segments. By scaling, rotating, translating and copying these segments interesting animations can be constructed without a lot of effort. Could the same be true with music? Here are the primitives I developed to find out:

  1. Sound - a sound consists of a frequency, duration and volume (gain).
  2. Stack - a collection of items (sounds, stacks or scores) that are all played at the same time. I think this may be similar in concept to a chord.
  3. Score - a collection of items (sounds, stacks or scores) that are played sequentially.

By now, those familiar with music theory are surely shaking their heads. But from a coding perspective, there's a nice symmetry to working with the above.

Using these classes, I can programmatically build songs:

Conductor.play(function(ctx) {
  var left = new Score();
  for(var f = 100; f < 800; f += 100) {
    left.add(new Sound().frequency(f));
    left.add(new Sound().frequency(0).duration('/', 2));
  }

  var right = new Score();
  for(var i = 0; i < 9; i++) {
    right.add(new Sound().frequency(200).duration(.25));
    right.add(new Sound().frequency(0).duration(.5));
    right.add(new Sound().frequency(400).duration(.25));
  }
  
  return { song: new Stack().add(left).add(right) };
});

You can listen to this creation by clicking here:

And here's another example:

I was pleased at how quickly the code came together. And I do love the compositional nature of the system. But man, is making music hard! In fairness, I've got about 20 minutes of experimentation under my belt. I currently have the same set of skills a toddler has when he bangs on your piano.

My hope is that with a little research I'll get a better sense of what patterns lead to a more pleasant sound and then my career as amateur musical composer will be truly off and running.

In the mean time, feel free to grab my code and make suggestions as to what I should do to improve the system.

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails