Mar 072013
 

Found this guy through pitchfork. So what? You going to make a big deal out of it now? You want to go?

Arthur Ashin is the man’s real name, and–no surprises here–he’s a Brooklyn resident, wetting the panties of the thick-glasses wearing, male falsetto lovers all throughout the New Manhattan. But notice the hypocrisy here: my supposed cynicism doesn’t change the fact that I am writing about this guy, and I do love the music that I’m hearing. So what’s up with that?

Let’s get real here. We could talk about the music itself. We could talk about the top-knotch production–the mixing is so virtuosic I’m tempted to use the word orchestration. We could talk about the timbral fluency that makes songs like Gonna Die possible, where a synthesized oboe flows seamlessly into a vocal wail. Or we could just admit the truth: Ego Free Sex Free is a great song. Critical language lets me achieve some distance: I can advance phrases like “bold re-imagining of funk” or “gentle yet firm weaving of gospel and synth-pop,” but the fact of that matter is that this song is successful because it achieves the impossible: it makes me want to fuck. We’re talking about me, for whom the act of sex falls somewhere between flossing (necessary but not altogether pleasant) and gardening (I can see how other people might get into it but really it’s not for me), and yet the bald truth is that this song makes me want to get it on.

If we go one level deeper, getting real is exactly what makes me want to write about this album. In a number of ways, it’s pure pop cotton ear candy of the worst kind: easy to slurp beats supporting insipid synthesizers and men crooning with love-anguish. But I can’t shake the idea that the choice of this democratized musical vocabulary is exactly what makes this album so good. From Nietzsche: Poets muddy their waters to make them seem deeper, and yet in spite of his poetic language Autre Ne Veut’s waters are crystal clear. Maybe you’ve read the Borges short story “Pierre Menard, Author of the Quixote”? If not go goddamned read it now. In it, the narrator describes a man named Pierre Menard who tries to rewrite Don Quixote exactly, not by copying the original work but rather by arriving at it. He wants something insane: to rewrite an extant work for himself, as if he had conceived of it independently. The narrator shows us why this exercise is relevant by critiquing one passage each from the original Don Quixote and from Menard’s version–the same exact text, in fact–and arriving at two completely different readings. One version, the narrator asserts, is the pompous borborygmus of Cervantes, the other is an unexpected and delightful quip from the upstart Menard.

Listening to Anxiety, I can’t help but think of the phrase “white man’s funk”. At the same time, I wonder if it’s impossible that Ashin didn’t copy funk but rather arrived at it, exactly as Menard hoped to arrive at the Quixote. Of course it’s extremely unlikely, but the fact that we can even consider it as a possibility speaks to exactly what I find to be Anxiety’s most engaging attribute: its honesty. Ashin doesn’t concern himself with the fact that the instrumentation, the groove and yes, the male falsetto, have all been heard a thousand times before. They remain, for Ashin, exactly the right tools for the job, and as a happy listener I can’t help but agree.

Dec 122012
 

1. More than anything, this Christmas I want to try to get as little unnecessary stuff as possible. That means that while I love a gag gift as much as the next guy, this Christmas I’d rather get only things that I really need or things that don’t generate any waste. I cannot stress this next point enough: Don’t feel any pressure to get me anything. If in doubt, err on the side of not getting me anything. If all you want to do is call me up on Christmas and offer up some warm feelings, that would mean a million times more to me that a thoughtful but ultimately over-packaged gift.

2. I really need financial help. That’s not to say that I need money, but rather that I need to know what to do with my money. One extremely nice thing you could do for me this Christmas would be to tell me how to do things like save and invest and all that good stuff. Bonus points for being creative and helping me find a financial outlet I might not have found otherwise. Advice like “invest in a diverse mix of stocks and bonds” is not particularly helpful. I want to know things like how to I make smart investments that also have a positive impact (green energy investments maybe? But which ones?).

3. Knowledge is a great present and yet somehow it doesn’t seem to be something that anyone ever gives or receives. I’m sure you know how to do something awesome, like skydiving or basket-weaving. Why don’t you tell me how to do it? Send me a how-to guide to get me started. Point me to a blog or gallery or some other kind of resource to get me inspired.

4. Make me something. Anything, seriously anything. Don’t worry about whether or not I’m going to like it–the important thing is that you enjoyed making it.

5. I do sort of want this book, although I would prefer the Kindle version. That goes for any book you were thinking of getting me, actually. http://www.amazon.com/Thomas-Jefferson-The-Art-Power/dp/1400067669/

6. I love to read, so books are always a safe bet. Books on music theory, ethnomusicology, history, mathematics and radical philosophy are the safest of the safe. And of course, fiction can’t help but be a winner. I’m big into Latin American fiction, as always, but I’m also getting into Murakami and Bolaño, emphasis The Savage Detectives.

7. Music, of course. Just stay clear of rock and roll, bluegrass, country and blues–all valid forms of music I’m sure, just not genres that excite me.

8. I’d really like to learn Spanish. If someone wanted to buy me a subscription to the Rosetta Stone, that would be amazing.

Dec 122012
 

So don’t get me wrong, I’m aware that it’s more than a little presumptive to write an essay on the internet and to assume that someone will read it. However, I really do think the message is important, and if I’m able to change the behavior of even one person then I think it will have been worth wasting everyone else’s time. Having said that, it is 2012–if Jesus were alive today even the sermon on the mount would have a tl;dr.

So.

tl;dr: This Christmas, don’t buy me anything. In fact, don’t buy anyone anything.

The problem with holiday season purchases is that they make us especially likely to be victims of product lifestyle ignorance. We buy things that are cheap and that we know will make good gifts, but we are ignorant as to how those things were produced or where they will go when we have finished playing with them. Without our knowing, our innocent desire to make our friends happy can make us unwitting sources of social and environmental toxins.

But how can some innocent Christmas shopping make us into bubbling geysers of dickishness? Well, let’s suppose we have a friend named Jack. Consider the parable of Jack and the avocados.

Being a vegetarian (though certainly not a devout vegetarian), Jack knows how hard it is to find good, vegetarian sources of protein. Most vegetable matter has almost no protein content at all, and what little does usually doesn’t even have the decency to present itself as a complete protein. So when Jack sees a healthy stack of avocados at 79 cents a pound, he gets more than a little excited. “Pinch me,” he says to no one, “I must be dreaming.”

He makes his way over to the avocados. He picks one up, hefts it–slightly heavy for its size–squeezes it gently and finds that it yields more than a little sensuously to his firm, even pressure. These avocados are perfectly ripe. They are offered at a fair price. Jack loves avocados. It might seem like a guarantee that Jack is going to walk out of the supermarket laden with creamy-green goodness, maybe even with some jalapenos and cilantro and dreams of guacamole. Instead, after looking at the signage above the avocados, Jack walks away without so much as a second glance. He even approaches a shelf-restocker and informs him about his onanistic produce escapade, including the reason that he chose not to buy the avocado: Capitalism.

Capitalism turns every purchase into an exercise of political power. The smallest, most incidental purchase can have a large impact, especially in aggregate. Buying an avocado increases the demand for avocados, which bolsters incentives to supply avocados, which leads to more infrastructure devoted to the transportation, refrigeration and distribution of avocados. This is the basis (and the elegance) of the capitalist system: the allocation of resources emerges organically from the demand for those resources. The specific chain of cause and effect that transforms the purchase of avocado A into market transformation T is Byzantine in the extreme, but without getting lost in the details this much is certain: something happens.

All this is hardly a revelation. The act of purchasing some good is a political act; participating in capitalism through exchange can and is in fact expected to have repercussions beyond the atomic exchange of money and good. “So why didn’t I buy that avocado?” says Jack, to a man that almost certainly doesn’t care. “Because while I love avocados more than I love most things, the sign says that these were flown in from Ecuador. I can’t bring myself to buy an avocado that has been made artificially inexpensive by exploiting cheap foreign labor and lax agricultural legislation.”

In other words, Jack is saying that he is not going to fall victim to the phenomenon of product lifestyle ignorance. When we go out and buy something, we say a number of things, some consciously, others unconsciously. At the level of our awareness, we assert that we are in favor of the good in question. “Yes,” one might say, “This avocado is something that I want in my life, and I don’t mind paying 79 cents apiece to have it.” Up until recently the conscious assertion may have stopped there, although these days, especially in the arena of food the average consumer has a lot more on his mind when he goes out to make a purchase. “I appreciate that this food was grown locally,” or “without pesticides,” or “both.” But this higher level of awareness is usually restricted to food, which is why on leaving the supermarket Jack can’t help but buy one of these, a plastic novelty action figure in the likeness of Jesus Christ.

http://mcphee.com/shop/jesus-action-figure.html

This is the problem with the way we shop during the holidays. Some combination of holiday stress, whimsy and intoxication shuts down the parts of our brain responsible for making smart purchases. We buy things that have no value other than novelty or symbol, things that will cause riotous laughter for a minute and then head straight to the trash. We buy things produced using exploitative labor and wasteful materials, or things that will spend centuries leeching poisons into some landfill once they’ve served their holiday usefulness. We buy plastic garbage that does nothing more than help us avoid the social stigma of not getting anything.

This Christmas, let’s break with tradition and not buy anything. Most of the things that we would buy are only useful as symbols or concepts anyway, so this Christmas why not get each other something symbolic? Let’s exercise our artistic gifts: paint someone a picture or write someone a poem. Let’s share our knowledge and expertise: explain how to do something that excites you to a friend who’s always been curious. Let’s spread some generosity: donate to a charity in someone’s name or better still, find a friend in need and devote some earnest, focused time to helping them.

After all, the currency of Christmas is love, not currency.

Sep 162012
 
iTunes Logo

A lot of the time when I download a song from Soundcloud, it ends up being a flat .wav or .mp3 file that looks something like this:

That is to say, <artist name> – <song name>.mp3. That’s fine and dandy, except when I go ahead and drag it into iTunes it ends up looking like this:

Which is close, but not exactly what I wanted. Unfortunately the song itself apparently didn’t contain any metadata, and iTunes doesn’t know how to separate the name of the song and the name of the artist from the original filename. The best it can do is guess that the name of the song is the song-artist hyphenate, which is cute but wrong. Fixing this mistake for a single track is no big deal, but after hand editing a number of tracks it gets to be a pain in the ass. That number may be large or small depending on mood, patience and overall caffeination. For me that number is 2.

Time for some automation. Apple’s Automator, ever the screwdriver to the world’s nail, is almost but not quite the right tool for the job. I was able to get a solution I was happy with using one of Doug’s AppleScripts for iTunes, which are well documented, free and most importantly relatively painless to fine-tune for that personal touch, unlike Automator actions.

Step 1: Download and install the script named First Item to Tag. This sexy little script will take the songs you’ve selected and split them at the ‘-’ charater. It will then prompt you as to whether you’d like the first item to be set to Artist, Composer, Album or one of a couple other tags. Then it does all the renaming for you, which is pretty great.

Step 2: Import all your songs into iTunes and then select them. You may have something like this:

Step 3: Just select the “First Item – To Tag” option from the little scripts menu

Select ‘Artist’

And just like that…. it didn’t quite work.

Step 4: Roll up your sleeves and get ready to hack the Applescript. I know, that prospect terrifies me as well, but fortunately we only have couple of lines to add. If you installed Doug’s iTunes script as intended the you should have a file called \First Item – To Tag.scpt\ at ~/Library/iTunes/Scripts. Open that file for editing. Add the following code:

			set target to first item of my text_to_list(tnom, sep)
			set target to my chop(target)

after the line that reads “set tnom to (get name of aTr)“. The result should look like this:

That should be it. Save the file and head back to iTunes. Select the list of files you want to update, follow the prompt and you should see all your songs updated correctly.

Awesome. A lot of painful research and one hacked Applescript later and we’ve got things just the way we want them. Not exactly the Apple way, but then this iTunes the bloated software beast we’re talking about. Maybe one day we’ll have flexible, extensible plugin support for iTunes… probably around the time iOS goes open source.

Aug 162012
 
SublimeCollider

Well, SuperCollider is great.

I don’t know why exactly it had taken me so long to figure out, but here at long last, wheezing away my last hours at the wizened age of 24, I am finally willing to admit that SuperCollider can make beautiful sounds, is entirely worth playing around with, and that my time spend literally down the hall from James McCartney while working at Apple was utterly, completely squandered. But enough crying over spilled milk. Let’s get started.

PART 1: INSTALL

Not so hard to figure out, huh?

I’m running OS X, obviously, because I absolutely do not have the energy for technological debates and prefer instead to use the most expensive, least fussy hardware I can get my hands on. As you can see, SuperCollider looks at my burgeoning laziness and says yes, by all means, have a drag and drop installer. Thanks, SuperCollider, for making my life simple. So, I simply move the SuperCollider folder into Applications, launch SuperCollider and then…

No

Nope. Not going to happen. That is not a UI, I am absolutely not going to spend any more time in this application than it takes to find the quit button.

PART 2: MAKING IT NOT SUCK

Okay, so I’ve officially complained and scratched my neckbeard, now to roll up my sleeves and fix this mess. The first step is to hook yourself up with Sublime Text 2, an absolutely superb text editor in one delicious flavor. Next thing you’ll want to do is to download and install the SuperCollider Package from Geoffroy Montel. I know it says that the package hasn’t been tested on OS X, more on that in a minute.

After you’ve done all that, the critical thing to do is to modify SuperCollider.sublime-settings so that sc_dir and sc_exe point to the correct places. Unfortunately if you don’t do this correctly the SuperCollider commands within Sublime Text 2 will silently fail instead of telling you anything useful; double unfortunately the documentation tells you that sc_dir is the important one whereas for me sc_exe is really what mattered. Plumbing through the python code in SuperCollider.py, it looks like the “Start sclang” menu option launches a SuperCollider subprocess by running the sclang script. That’s all dandy, expect I was having the problem that Sublime Text 2 couldn’t launch SuperCollider because it couldn’t find sclang, even though I’d added it to my path. I don’t know how to fix this except to modify SuperCollider.sublime-settings so it looks like this:

// SCLang command name
"sc_exe": "/Applications/SuperCollider.app/Contents/Resources/sclang",

It looks like you can set sc_dir to whatever you want. I set it to be the root directory for all my SuperCollider projects. Anyway, once you’ve done that you should find that “Start sclang” actually works.

Okay, so syntax highlighting – check. Starting sclang remotely – check. Evaluating and listening to a delicious sine wave – check. And now for stopping audio…… Hmm. Well. That’s shrill. The basic problem, on my machine at least, was that Sublime Text 2 wasn’t sending a newline character to SuperCollider after telling it to stop audio, so that line wasn’t getting read. For me the solution was to modify SuperCollider.py like so:

--- Sc_startCommand.sclang_process.stdin.write("thisProcess.stop;\x0c")
+++ Sc_startCommand.sclang_process.stdin.write("thisProcess.stop;\n\x0c")

See that extra newline character? Made all the difference.

Finally, my last big complaint was the command “Evaluate current line”. Such a command would be great, if everything I ever wanted to do could live on a single line. Of course, this is SuperCollider and not Malbolge, so I appreciate being able to understand my programs when I look at them. So, I again modified SuperCollider.py, in the following way:


for l in lines:
--- Sc_startCommand.sclang_process.stdin.write(l.encode("utf-8","ignore")+"\n")
Sc_startCommand.sclang_process.stdin.write("\x0c")
Sc_startCommand.sclang_process.stdin.flush()


for l in lines:
+++ Sc_startCommand.sclang_process.stdin.write(l.encode("utf-8","ignore"))
+++ Sc_startCommand.sclang_process.stdin.write("\n")
Sc_startCommand.sclang_process.stdin.write("\x0c")
Sc_startCommand.sclang_process.stdin.flush()

Hopefully that makes sense. Instead of sending a newline after every line, I just send a newline after the whole block.

PART 3: HOLY SHIT SUPERCOLLIDER

No, but seriously, this is an FM synthesizer (kind of):

var playFM;
playFM = { arg cFreq, mFreq, mDepth;
	{
		var mod;
		mod = SinOsc.kr(mFreq, 0, mDepth, 0.0);
		SinOsc.ar(cFreq + mod, 0, 0.2);
	}.play();
};

playFM.value(400, 10, 10);

Can you believe that? Can you believe that shit? What is this, javascript for sound? Look at line 6, for Putin’s sake. That’s where I add an integer, a simply, god-fearing, salt-of-the-earth integer to a class, to a Unit Generator, whatever that is, and I pass the whole stupid thing as an argument to a constructor function, which returns an object whose frequency is modified by another object. Fucking what? Okay, it was a pain to get Sublime Text 2 all set up, but now I’m excited.

Jun 282012
 

I am fascinated by the idea of structure in music.

It could be the nerd in my speaking (it usually is) but I love the idea of taking a piece of music and dividing it up into its constituent parts. I actually get gooseflesh when I think about sitting down with a tight, well composed piece of music and unraveling it like a Persian rug, one thread at a time, just to see how it all hangs together. Surely one doesn’t have to be a nerd to enjoy music this way–the difference between music and noise is, by definition, order–so what anyone enjoys with a piece of music must be the relationships and structure of the sounds involved. But I think there is a secondary thrill to be had by people like me who like to understand music, who like to wander into the wilderness of music and attach names and labels to everything. Some people might think that there’s some sacrilege to putting a piece of music on the autopsy table but I couldn’t disagree more. Understanding music is like understanding anything else. It’s one thing to come to know, through trial and error, which herbs can treat which diseases. It’s another thing entirely to understand the body; understanding not only reveals newer, better treatments but also helps us see the beauty of the human body.

As I write this my sister is currently halfway across the country, on a bike ride from Baltimore to San Francisco. I’ve been thinking that I’d really, really like to have some music composed for her by the time she makes it to California, as a kind of congratulations. I’m inspired by exercise music, by which I don’t mean the music that people listen to when they exercise but rather that kind of music that gets into your head when you start running or biking, that pounding, repetitive, endurance monologue that keeps you pushing uphill or rolling through intense summer heat. Part of my wants to sit down and write something linearly, starting with a paper and pen and ending with a piano piece. At the same time I think this is an excellent opportunity to investigate how structure can bring forth a piece of music. I’m wondering what happens if I start with the structure and then build the music out from there. How will my structure differ from traditional forms? Will the structure be evident in the music? Most of all, will it sound any good?

For my structure I’m choosing, unsurprisingly, the cycle: a small melodic unit of between, say, three and eight notes. Of course, creating a piece of music by overlaying looping samples is by this point perhaps the most well-worn territory in the history of music. The process, though, is a bit chaotic. It’s simple to launch a bunch of musical clips of different length all at once, and already I know that simply by overlaying these musical units I can achieve a huge wealth of effects, from changes in tempo and density to rich and evolving harmonic structure. At the same time, it’s hard to know exactly how a given group of cycles is going to sound together. With two cycles of unequal length the number of harmonic combinations is the least common multiple of the two cycle lengths. Enumerating and understanding each of these combinations is difficult enough for pairs of cycles; for a greater number of cycles it becomes an intractable problem.

The problem is one of resolution. Creating a tight, coherent piece of music requires controlling parameters at several different scales across many domains. To modulate from one key to another, for example, the composer must first think of the modulation in terms of the musical elements he has so far established. He has to transpose his melodies and harmonies to the new key, while simultaneously deciding how that shift to the new key will affect the fine structure of those melodies. At the same time he has to manage the modulation itself, paying close attention to each voice as it moves from one key to another. Each voice must trace a self-consistent path from one key to the other, each voice must reinforce each other as it moves, and each voice must come to rest in a manner that establishes the new key. Finally, the modulation must itself make sense in the context of the piece as a whole. Managing all these interwoven constraints is exactly the skill that the composer must hone over years of practice, and it is exactly why composition requires so many long hours of formulation and reformulation.

My goal is to figure out how to layer cycles of notes in an intelligent way, holding on to a higher order structure that will bind and direct each cycle in a way that makes musical sense. Typically that higher order structure is provided by the composer, who chooses when to launch each cycle and how to vary higher level control parameters over time, giving shape to the composition. House music, trance music, hip-hop and other genres built around the clip all obey this principle to a greater or lesser extent. I’ve had an insight that I’d really like to explore and that’s this: what if I make everything a cycle? What if groups of notes are cycles, as is traditional, but groups of instructions are cycles as well? What does that mean exactly? Well, take a group of notes like this:

Four notes repeating in a loop. Now, what if I apply a higher-order cycle, where the notes of that cycle are actually instructions that affect how the loop should be played? In this case, let’s say that the note-loop has four quarter notes while the instruction-loop has four whole notes. If the instruction is a modulation, then the result might sound something like this, if we only modulate the last whole-note:

Now we’ve created a 16 beat loop from two 4 beat loops. Notice too that we can control two different resolutions. We can control both the structure of each 4 beat loop as well at the modulation of each 4 beat loop within the 16 beat whole. That’s pretty neat, and it’s just the kind of multi-resolution control around which I’m want to try to build this piece.

Here are some more examples, with different tempos, loop lengths and loop note values:

In the next post I’ll talk about the max patch I used to explore this idea, and I’ll go through how I made it.

 Posted by at 5:58 pm
Jun 292011
 

Sometimes, Apple, I actually don’t give a shit how extensible and optimized your audio stack is. I admit, it’s pretty cool that you can build aggregate devices out of several hardware drivers without having to touch the kernel. But I’m not building a low-latency, sample-accurate, cosmos-shaking space synthesizer. I’m making a crummy little iPhone game, and I don’t want to go on a grand tour of the unimaginably complicated Core Audio API just to find out how many samples are in a file.

How about this: I give you the name of a file and you give me back an array of samples. No, shut up, stop trying to tell me that audio files can have different sample rates, or that samples can have different sizes. I do not give one little-endian shit. No, I don’t want to waste an afternoon trying to figure out the difference between frames and packets and samples. And no, I don’t understand why you think error code -10868 is a reasonable explanation of what went wrong, or why you think the only way to figure out what that error means should be to look it up in a private header. That does not count as documentation.

Come to think of it, why am I suddenly writing in another language entirely? There I was, blissfully cruising along the Cocoa highway, and now suddenly I’m squatting in a roadside ditch trying to remember how C function pointers work. I just wanted to know how long my audio file was. I’m not completely thick, I get that Core Audio has to be super low-latency and that certain sacrifices had to be made. Does that mean that to read a sound file I should have to first ask it for its sample rate, then tell it its own sample rate, then ask how long it is, then tell it that I want that many samples, all while trying to figure out what the everloving fuck a AudioBufferList is and how I can possibly allocate one without making my head explode?

No. I’m standing up and I’m saying no. The audio learning curve should not be this steep. It should not be trivial to play a short sound, easy to play one sound with high latency, and an Euler problem to get an audio file’s sample rate.

Sorry, /rant. Anyway, here’s the code to do what I wanted to do. I recommend you just copy and paste it. You’re going to need some files from PublicUtility in /Developer/Extras/CoreAudio, BTW.

Here’s an example usage:

CFULRRef fileURL = (CFURLRef) [[NSBundle mainBundle] URLForResource:@"sound" withExtension:@"wav"];
AudioBufferList *ioData = OBAudio::AllocBufferListFromAudioFile(fileURL);

And now you’re done. That’s it. Go outside, see a sunset, find love.

//
//  OBAudioFile.h
//
//  Created by Sam Tarakajian on 6/28/11.
//  Copyright 2011 Otherbirds. All rights reserved.
//

#import <AudioToolbox/AudioToolbox.h>
#include "CAStreamBasicDescription.h"

#ifndef d_OBAudioFile
#define d_OBAudioFile

namespace OBAudio {
    
    static Boolean AudioFileFormat(CFURLRef fileURL, CAStreamBasicDescription *outDesc)
    {
        OSStatus result;
        ExtAudioFileRef audioFile;
        UInt32 propSize;
        
        result = ExtAudioFileOpenURL(fileURL, &audioFile);
        
        if (result) {
            ExtAudioFileDispose(audioFile);
            return false;
        }
        
        propSize = sizeof(*outDesc);
        
        result = ExtAudioFileGetProperty(audioFile, kExtAudioFileProperty_FileDataFormat, &propSize, outDesc);
        if (result) {
            ExtAudioFileDispose(audioFile);
            return false;
        }
        
        ExtAudioFileDispose(audioFile);
        
        return true;
    }
    
    static UInt32 AudioFileSampleLength(CFURLRef fileURL)
    {
        OSStatus result;
        UInt32 propSize;
        SInt64 fileLengthInFrames;
        ExtAudioFileRef audioFile;
        CAStreamBasicDescription outDesc;
        AudioFileFormat(fileURL, &outDesc);
        
        result = ExtAudioFileOpenURL(fileURL, &audioFile);
        if (result) {
            ExtAudioFileDispose(audioFile);
            return 0;
        }
        propSize = sizeof(SInt64);
        result = ExtAudioFileGetProperty(audioFile, kExtAudioFileProperty_FileLengthFrames, &propSize, &fileLengthInFrames);
        if (result) {
            ExtAudioFileDispose(audioFile);
            return 0;
        }
        
        ExtAudioFileDispose(audioFile);
        return fileLengthInFrames;
    }
    
    static Float32 AudioFileSampleRate(CFURLRef fileURL)
    {
        CAStreamBasicDescription clientFormat;
        AudioFileFormat(fileURL, &clientFormat);
        
        return clientFormat.mSampleRate;
    }
    
    static UInt32 AudioFileNumChannels(CFURLRef fileURL)
    {
        CAStreamBasicDescription clientFormat;
        AudioFileFormat(fileURL, &clientFormat);
        
        return clientFormat.mChannelsPerFrame;
    }
    
    static AudioBufferList *AllocBufferList(UInt32 bytesPerFrame, UInt32 frameLength, UInt32 channels)
    {
        UInt32 numBuffers = channels;
        UInt32 channelsPerBuffer = 1;
        AudioBufferList *ioData;
        
        ioData = static_cast<AudioBufferList *>(calloc(1, offsetof(AudioBufferList, mBuffers) + (sizeof(AudioBuffer) * numBuffers)));
        
        ioData->mNumberBuffers = numBuffers;
        
        for(UInt32 bufferIndex = 0; bufferIndex < ioData->mNumberBuffers; ++bufferIndex) {
            ioData->mBuffers[bufferIndex].mData = static_cast<void *>(calloc(frameLength, bytesPerFrame));
            ioData->mBuffers[bufferIndex].mDataByteSize = frameLength * bytesPerFrame;
            ioData->mBuffers[bufferIndex].mNumberChannels = channelsPerBuffer;
        }
        
        return ioData;
    }
    
    static AudioBufferList *AllocBufferListFromAudioFile(CFURLRef fileURL)
    {
        OSStatus result;
        ExtAudioFileRef audioFile;
        CAStreamBasicDescription outDesc;
        AudioFileFormat(fileURL, &outDesc);
        UInt32 bytesPerFrame = outDesc.mBytesPerFrame;
        UInt32 frameLength = AudioFileSampleLength(fileURL);
        UInt32 channels = AudioFileNumChannels(fileURL);
        
        AudioBufferList *ioData = AllocBufferList(bytesPerFrame, frameLength, channels);
        
        result = ExtAudioFileOpenURL(fileURL, &audioFile);
        outDesc.SetCanonical(channels, false);
        ExtAudioFileSetProperty(audioFile, kExtAudioFileProperty_ClientDataFormat, sizeof(CAStreamBasicDescription), &outDesc);
        
        UInt32 framesToRead = frameLength;
        
        for (int i=0; i<10; ++i)
        {
            ExtAudioFileRead(audioFile, &frameLength, ioData);
            
            if (frameLength == framesToRead) break;
            frameLength = framesToRead;
        }
        
        if (framesToRead != frameLength) {
            free(ioData);
            ioData = nil;
        }
        
        ExtAudioFileDispose(audioFile);
        
        return ioData;
    }
}

#endif // #ifndef d_OBAudioFile

Jun 152011
 

In case you didn’t know, I am a phenomenally lazy person. There is a layer of detritus on the floor of my room so thick you could stand a spoon in it. Four months ago I filled out a form to get health insurance, the only thing left to do was fax it in. I still don’t have health insurance. But whatever, what some people call laziness I call efficiency. That’s how I found out about the Karplus-Strong algorithm: trying to get a lot of sound for very little effort.

From what I can gather, the Karplus-Strong algorithm is just a very simple model of a physical sound source. Almost every physical modelling algorithm I can think of consists of two main parts: the energizing force and the resonating body. You can get as fancy with it as you like, adding all sorts of filters and feedback and whozits and whatnot, but at the end of the day something bumps into something else and that something makes a noise. And without getting too technical that’s all Karplus-Strong is.

How does it work?

There are two main pieces: a burst of noise and recirculating delay line. The noise just provides broad-spectrum energy; the delay line is responsible for most of the character of the resulting sound. What’s critical here is that the time the sound spends in delay before it reenters the delay buffer be less than a certain amount. If the delay time is too long, all you’ll hear is a noisy pop with a long echo. As the delay time gets smaller and smaller, the effect of the recirculation starts to move from the time domain to the frequency domain, and you end up with a comb filter. Say your noise burst contains some frequency at 440 Hz. If the delay line is of just the right length–1 over 440 seconds (about 2.2 milliseconds)–then any 440 Hz frequency component that goes through the delay line will have waited just long enough to interfere constructively with other 440 Hz components both in the input noise and recirculating in the delay line. The result is that frequencies at 440, 880, 1320 (and so on) Hz will be emphasized, and all other frequencies will be attenuated by an amount proportional to how out of sync they are with the delay line.If you plot the result on a spectrogram, the result looks like a comb with teeth at all the resonant frequencies. Hence the comb filter.

You probably noticed that the spacing of the resonant frequencies on such a delay line happen to be nice whole-number multiples of each other. This makes the KS algorithm especially well suited for making simple harmonic sounds with just a bit of grit. The amount by which you multiply the sound added back to the delay line has a large effect on the character of the sound as it resonates. Setting the constants to larger values both lengthens the decay time and sharpens the teeth of the comb, so to speak.

What now?

I think there’s probably four parameters worth controlling in the basic Karplus-Strong algorithm. First is the length of the noise pulse used to kick off the resonantor. Actually, it’s pretty surprising just how much you can shape the resulting sound based on this parameter alone, the effect being particularly striking for string sounds. I find that if you vary the length of the noisy impulse, you can cover a whole range of string articulation from bowed to strummed to plucked to pizzicato. If you want to get fancy you can even add a nice, shaped envelope to the noise burst. If you’re feeling downright bourgeois you can even throw a low frequency oscillator on it.

Once you’re done messing with the length of the noise burst, try switching from a white noise source to some other noise source. Brown noise always makes me especially happy, partly because the mental image is hilarious (I always, always see a weird swarm of brown static engulfing New Jersey), but also because I like the noise. I don’t know that Max has a straight-up brown noise generator (though you could code up an external in a femtosecond), but you can get a reasonable approximation with the rand~ object. Rand~ is usually used for doing things like getting a chorus effect since it lets you get random values with a signal at a rate much slower that your current sampling rate. But rand~ is like the spork of the sonic kitchen: you can also use it to make a special kind of noise with energy concentrated in a specific range. I happen to find the combination of rand~ as a noise source and the KS resonator to be particularly pleasing.By changing the frequency of your rand, you basically change the “stiffness” of your resonator. I guess. That’s what it sounds like to me anyway. Higher values give you a metallic sound, lower values sound mellower and more subdued.

Beyond these two parameters you can also mess with the length of the delay line and the amount by which you multiply sound added back to the delay line. Naturally, changing the length of the delay line changes the perceived pitch of the resonator, and changing the recirculation constant changes, well, the amount of recirculation. Pretty self explanatory.

What else?

It’s Max, baby, do whatever the hell you want. There’s no law, up is down, black is white, cats and dogs living together and junk. One obvious place to start is simply to add more KS resonators. I bet you could get a really cool sound just by layering a whole bunch of Karplus-Strong’s's. If you were really into the whole modelling side of things you might try to reproduce the sound of a wood-bodied string instrument with sympathetic strings. Some guitar-like instruments have these little metal strings on them that aren’t meant to be played directly but rather modify the timbre of the final sound. You could even feed the result of one KS resonator into another, then back into the first, then bitcrush, then ring mod… you get the idea.

If you’ve looking for something really interesting to do, try adding a couple relatively steep bandpass filters to the noise pulse.I wonder if you space them like formants if you can’t make a KS resonator that sounds like it’s making vowels. Oh my god, a Karplus-Strong vocoder? Somebody get on that shit.

 Posted by at 7:06 pm