Hire me!

Well, as previously reported, I got caught up in a big layoff from Disney Interactive / Playdom. Considering the amount of time I was there, I got treated pretty well and that has allowed me to take a couple of months off completely. Actually, without getting into details, I kind of can’t start another full time job until early May. But it’s all good. Very good. I’ve been enjoying the time off immensely. I could get used to this. But eventually, the clock will strike midnight, my coach will turn into a pumpkin, I’ll have to leave the ball and go back to scrubbing cinders.

I haven’t been job hunting in earnest, but have had some interesting conversations that I need to follow up on. I guess over the next few weeks I will have to get more serious about this.

I did manage to pick up some contract work. I’ll be creating an online video-based course to teach basic JavaScript. This will be six lessons, each 30-45 minutes of video each. I spent the last week finalizing the outline and getting to work on Lesson 1. I’m really excited about this and I’m having a lot of fun doing it. This is exactly the kind of work that I would love to be doing full time. And it’s a nice extra income that pushes off that pumpkin deadline a few more weeks into the future as well.

I already mentioned this in my previous post about being laid off, but since then I’ve been doing even more “soul searching” about what I want to do and this is it. All recent controversy aside, I’d love to get into someplace like Mozilla, working with the MDN documentation or something similar. Or any other company that has an API, a service, a language, system, framework, etc. that they want people to understand and use to its full potential. I just love learning something, then analyzing the hell out of it in order to teach it to others, showing them A. why they might want to use it, B. how easy it is to use and how to get started, and C. some awesome things you can do with it.

Alternatively, I’d also love to get into something even more purely educational, such as Khan Academy, Udacity, Lynda.com or something like that. That’s basically what I’m doing now with this JavaScript course contract. I’d be happy to continue doing contracts like this, though the illusion of job security with full time employment still has a hold on me.

I’m also not at all averse to continuing on in a straight up developer role somewhere. But if so, I’d love to be somewhere where I could start projects and do some creative work, not just be a member of a large team handling a conveyor belt of Jira tickets on some system created by someone who no longer even works there.

So, I’ll be continuing to do a more traditional job search kind of thing, but figured it couldn’t hurt to throw out a shotgun post like this. If you know of any leads or have any contacts in any companies that might be looking for people in positions like any of the above, please send them my way!

Posted in General | 6 Comments

Playing With Chaos – Alternate Formats!

Since I published Playing With Chaos on the Amazon store, people have been asking for alternate formats – PDF, epub, print. Well, I finally got around to cleaning it up and formatting it for PDF. Generating an epub from the Kindle .mobi format was easy enough. So you can now purchase DRM-free versions of the book from Gumroad:

https://gumroad.com/l/playingwithchaos

When you buy, you’ll get all three versions – PDF, epub, mobi. No DRM, so you can read them anywhere. Hopefully you won’t go crazy sharing them. Think of the children.

Posted in General | Comments Off on Playing With Chaos – Alternate Formats!

Goodbye, Magic Kingdom

Well, that was a bit fast.

At the beginning of last April, I started working at Playdom, the social gaming division of Disney Interactive. As part of the Central Tech team, I wound up working on maybe a dozen different games, from Star Wars to Pirates of the Caribbean. I’d usually just go on to a game team for a short time to help out with something specific – build process, some library integration, optimization, implementation of some specific feature, etc. – then I’d move on to some other team that needed some help.

A couple of months ago, there were some big internal reorganizations and a couple of key execs left the company. Then, a few weeks ago, the Wall Street Journal posted a story claiming there were going to be huge layoffs from Playdom. I didn’t hear about the story until the following week, which was after the supposed layoffs were allegedly occurring. Although I was told it was an unfounded rumor, I felt that there was probably some truth to it. Maybe the timing was off, but I suspected something was in the works. Lots of internal factors, such as major reorganizations, shifting production schedules and shifting technology decisions, made me wonder what a lot of employees were going to do.

So last Thursday, when New York Times announced that Playdom had laid off 700 employees, it didn’t come as a huge shock. Well, the fact that they used the past tense, and nobody in the office knew anything was a bit strange, but obviously something big was happening that day. It was an odd day to be a remote employee. But eventually I got THE CALL. And so, now, I am unemployed, along with 700 or so of my former coworkers.

As it turns out, it seems like Disney took pretty good care of the people it let go. I can’t complain at all about the deal I got, especially considering I’d been there just under one year. Without getting into details, it works out that I’ll be taking the next two months off. That sounds extravagant, but it’s not just me being lazy. It’s just how it’s going to work out, and it’s the only logical option. So I’m pretty psyched about that. In my 11 months at Playdom, I didn’t take a single vacation or sick day. So I feel like I’m ready for some time off. Two months to chill out and reboot and do some soul searching about what I want to do next. I can do some other projects or small contracts though, so if anyone would like some help on a project, let me know.

Some thoughts: I’m not sure I really want to go back into a production coding environment. Yes, I can track down and fix bugs in my or someone else’s code. Yes, I can implement new features in existing code bases. Yes, I can optimize and convert existing code. But I’d much rather be building things from scratch. And with my recent Coding Math series, it’s become clear to me that one of my strengths is in education. I’d love some kind of position where I could write documentation, tutorials, do videos, seminars, workshops, sample apps and implementations. So if anyone has a line on such a job, let me know!

Some of the projects I plan to work on during this “sabbatical” are:

1. Playing With Chaos. Several people have been asking for a non-Amazon version of the book, either PDF, other format, or print. I’d started the conversion of this a while back, and got back onto it recently. It’s mostly a lot of formatting work. The Kindle/mobi format is basically reflowable HTML, but PDF and print are page-based, so I need to go over each page and look at how it lays out – code line breaks, image spacing, etc. Anyway, I think I should have some alternate versions available very soon. And then I’ll look at a print version.

2. Coding Math – I was doing three videos per week, which was getting to be a bit much. I was about to post something saying that I was going to cut that down to two videos per week. But now that I have some free time on my hands, I think I’ll keep up the three-per-week schedule for a bit. Last week I only got out a single video due to the drama at the end of the week.

3. I’ve had a couple of game ideas floating around my head. I may try to get those out the door finally. And I need to do some updates to Falling Balls.

4. Woodworking. This is a recent hobby I’ve picked up. Still in the noob stages, but starting to create some half decent items. I have a small basement shop, so I’ve been concentrating on small boxes, toys and puzzles. I’ve been having a lot of fun with it. After so many years of making virtual goods, it’s quite a change to be creating physical items. Here’s some of my stuff. https://www.etsy.com/shop/SquareKWoodworking

5. Get back on track with current web technologies. I was getting into this more last year, but at Playdom I was back in the Flash/AIR world mostly. I still love JavaScript, but have probably fallen a bit behind on the current popular frameworks and technologies that all the cool kids are using these days. I’d like to ramp back up on that really quickly. Suggestions? I’ll probably go to a bunch of local meetups too.

6. I also started learning a bit of Unity at the end of my Playdom stint, as it seemed like we were going to be doing a lot more with that. I may spend a little time continuing to look at that stuff.

7. I’ll probably reboot my running activities. Since my third marathon last October, I’ve been in a real rut. Just can’t get into a steady running schedule for more than a week or two. Maybe with a little extra time, I’ll be able to get back into it.

Posted in General | 10 Comments

Coding Math Mini #5: Pythagorean Theorem and Distance

This is one I’ve been meaning to do for a while. Probably should have done it earlier, as it’s used in so many places. Anyway, here you go, how to find the distance between two points.

Posted in CodingMath | Comments Off on Coding Math Mini #5: Pythagorean Theorem and Distance

Coding Math: Episode 13 – Friction

I figure I might as well post these here too. Just in case people aren’t aware of them. πŸ™‚

Posted in CodingMath | Comments Off on Coding Math: Episode 13 – Friction

Coding Math Application Series

Last week I kicked off a new series on the Coding Math Channel. It’s the Application series.

I was thinking that it’s nice to present new concepts in each video, but there is a limited amount that I can do with them. I try to make the main episodes be 10-15 minutes long. I can explain a concept, do a few drawings, show some math, write some code, see it in action, and maybe iterate on that once or twice. And then, that’s it for that topic. Hopefully the brief example was good enough, because I’m moving on to something else now.

So my thought was to start another series where I actually build some simple app or game, or at least the barest outline of such. With some real world applications of the principles that are covered in the other videos. Each video will be in the five minute range, adding just one or two small features to the current app or game. Each feature may make use of one or more of the concepts from the other videos.

The first game is something I call Ballistics. It’s just a simple idea where you aim a gun and it shoots a cannonball that you try to hit a target. Like the old QBasic game, Gorillas.

gorilla2

In the first episode, we use a bit of trigonometry, including arctangent, to aim the gun using the mouse. In this week’s upcoming episode, we’ll actually get a cannonball firing, so that will use the particle class, with velocity and gravity, and lots more real world application of trigonometry. But each one is a bite sized piece of an application. We might hit the same concept over and over in different parts of the same app, or in different apps. But that’s the whole idea, to see many different ways you can use these concepts.

So now, we have the main episode each Monday, a Mini episode – shorter 5-minute simple concept – on Wednesday, and these Application episodes on Friday.

I want to thank all of you who have supported me on Patreon.com. It really makes doing these videos more justifiable in terms of the time I spend on them. And if you are a supporter, know that only the main Monday episodes are Patreon sponsored episodes. The Minis and Applications are on the house.

Posted in General, JavaScript, Technology | Comments Off on Coding Math Application Series

2013 in Review

For the last few years I’ve done a year in review type of post near the end of the year. I guess I blew that already. But January 1st isn’t a bad time to do it.

2013

2013 brought a big change for me. After almost 6 years of working at Infrared5, I left there to work at Disney Interactive. It was a tough decision. I started at IR5 because the people there were my friends. And more friends arrived over the years. But the company had started as a Flash shop and with the slow decline of Flash, I felt it was facing an identity crisis. Long story short, I felt I was stagnating there the last year or two and needed to move on.

Moving from a small company to a massive one like Disney is tough. Oddly, I find myself back doing a lot of Flash work. But really touching all kinds of stuff – Objective-C, C++, C#, JavaScript, Unity, Java. For a month or so I became the go-to Jenkins guy, setting up build servers for a bunch of different teams. That was a lot of fun. It can get a bit frustrating being on a massive team where you only own a small portion of the code and other people are working on other parts. I honestly prefer smaller projects that I can start from scratch, do the architecture and then start fleshing it out, with another person or two helping to do parts. Thus far at Disney I’ve mostly been jumping around assisting in ongoing projects for a few weeks to months. A kind of strike force of one. But when I’m done with the current project I’m on, I have a project lined up for 2014 that I’m very excited to get onto. Nothing hugely glamorous, but something I’ll be able to start up myself and be a lead on.

Other than work, I’ve started a couple other projects. Of course there was Playing With Chaos. That took up a few months of my spare time, but was a ton of fun and hugely satisfying to be able to pull off the self-publishing of a book. One thing I’ve realized publishers are good for is publicizing your book and driving sales. So it hasn’t exactly been a runaway best seller, but honestly, I don’t think it was ever destined to be. It’s a niche title. A labor of love.

And I started the Coding Math video series. This has also been very satisfying and keeps me excited on a weekly basis, planning out new subjects, writing scripts, recording and editing. I’m almost at the point where my own voice in my own ears doesn’t sound like fingernails on a chalkboard to me. And learning lots about the process as well. I can see myself that the quality of the videos has come way up since the first one, but still has a long way to go.

Earlier in the year, I decided to build an arcade cabinet. This never fully materialized, but did spark a new interest in woodworking and an old interest in electronics. I dabbled in both a bit, but both got pushed aside when I started working flat out on Playing With Chaos. But both will come in handy for a new project I’ll be doing this year…

Personally, things are good. I ran my third marathon on my birthday in October. It wasn’t my best, but not my worst either. Since that race, running has taken a back seat for me. Marathon training is a four-month process that takes a lot out of you. I’ve gone through it three times in the last two years.So the last month or two I’ve taken a break. I’ve also gained some weight. So I start this year temporarily in the worst shape I’ve been in in a couple of years! But still, it’s better shape than I was in the previous 10 years.

I got a dog! I never was much of a dog person. Could take them or leave them. Some people at my last job believed I hated dogs. Not true. There were something like 5-6 dogs in the office and it was a major distraction all too often. Anyway, my daughter Kris has been dying for a husky for years. I kept saying no. My wife was on the fence. She finally joined my daughter’s side and they ganged up on me. So now we have a husky named Yuki. They promised to do all the work, including taking her for long walks twice a day. Of course, at this point, I am the chief dog walker. But this has had its benefits. At any rate, Yuki has totally changed our lives and is a really awesome addition to the family and home.

A husky needs a lot of walking. So I’m out with her 30-45 minutes or longer twice a day. This has lead to a couple of new hobbies. One is history. I’ve been into audiobooks for a while, listening during my long runs. But I started listening to history lectures from The Great Courses. You can get many of them on Audible.com and I can also get a lot from the library as well. (Side note: my use of the library has rocketed since I discovered that you can go on line and search for and order books, movies, and audiobooks from a huge network of libraries around greater Boston and suburbs. I can find almost anything if I’m willing to wait a week or three.) I’ve listened to a couple about the American Revolution, the Rise and Fall of the British Empire, The Fall and Rise of China, and the Rise and Fall of Soviet Communism in Russia. On deck are ones on Hitler’s empire, more about China, and the French revolution. And a few non-history subjects I wanted to learn about. It’s been a fantastic learning experience so far, and I’m able to bore my family to death with fascinating (to me) facts.

Also, while walking the dog at night, I started looking up in the sky. When I started, I could recognize the Big Dipper and Orion. And from the Big Dipper, I could sometimes locate the North Star. The rest was just random specs of light. But they were up there every night so I started looking closer. Tried a few different star chart apps, and settled on Stellarium. I just use the desktop app, spot a few things to look for before I go out, try to find them while I’m walking the dog, spot some other patterns while I’m out there and try to figure out what those were when I come back in. I have an app on my phone too, but it’s tough to use when you’re walking a dog and listening to history lectures. πŸ™‚ I got up to the point where I could find and name more than a dozen constellations and more than a dozen stars as well as other features, including Jupiter and Venus. This past week I started thinking of getting a telescope to take things to the next level. Much of what I read said to start with binoculars. So I got a half decent pair and took them out last night with my daughter. Holy cow! The moons of Jupiter, the Andromeda galaxy, the Orion nebula! I’m now honing up on telescope basics and reviews. I need one.

2014

So what’s in store this year?

1. I’d like to get out a printed version of Playing With Chaos. This requires formatting a decent PDF version, which I may sell directly in addition to the Amazon sales.

2. I have another self-publishing book idea that I started working on. This will be smaller and probably even more niche, but it has to be done. More on that if and when it moves forward.

3. Of course, I’ll be continuing on with the Coding Math series. Currently this is my top priority.

4. As hinted to above, I have another project in mind that will make use of both my electronics and woodworking skills (minor though they both may be). I’ve gotten started on this, but have some parts on order, will need to order more, and then will have various fabrication issues to work out. Taking this one slowly, but will report when there’s something to share.

5. More learning, learning, learning. Stars, planets, history, technology, etc.

To sum it up, I quote from the best New Year’s resolution tweet I’ve ever seen:

My new year’s resolutions:

1. Read
2. Write
3. Execute

#chmod777

https://twitter.com/bobspace/status/417799321921126400

Posted in General | Comments Off on 2013 in Review

Announcing Coding Math Video Series

Those who know me personally, or have followed my work on this site for the last twelve and a half years (has it really been that long???) know that I go in and out of all kinds of programming subjects. From the early Flash experiment days I was always into math and physics and interactivity. I’ve created some fairly popular games (Falling Balls, Gravity Pods). I’ve enjoyed creating algorithmic art at www.artfromcode.com, of which several pieces have been published or used in various contexts. And I’ve had a couple of gallery shows with my art. I’ve coded various other mobile apps. I’ve created a couple of very popular UI component sets – BitComponents, which were purchased by a company called BeamJive and published under their own name, and later the open source MinimalComps, which enjoyed huge success and popularity. I’ve worked on various build and process management tools, such as STProjectMaker, which has been pretty popular itself. I’ve revived my love of electronics from my youth and have posted a few things on that, which people have found useful. And of course I’ve written a dozen or so books on coding and spoken at dozens of conferences around the world. This is all above and beyond any coding I’ve done in my day job. Not a bad hobby!

So I jump around a lot, but as time goes on, I’ve been struggling to figure out that one thing that really drives me. When all is said and done, I think it comes down to teaching and educating others. That’s the one thing that I keep coming back to. I love to learn something and distill it down to its basics and then teach others in a way that is way more clear and easy to understand than all the stuff I had to wade through to learn it in the first place. Even when I create some piece of art or a game, and don’t publish the source code for that, I still have an urge to explain to others how to achieve the same effect, or mechanic, or whatever.

That’s one of the things I initially loved about conference speaking. But more and more, conferences are highlighting the more inspirational speakers. “Look at all this cool stuff I did. Work hard and someday maybe you can be like me.” Even the more technical speakers are generally just promoting some methodology they subscribe to or framework they created. There’s generally little room for teaching or education other than the few full or half-day workshop spots that some conferences do.

Writing books is awesome, but is a long, drawn out, several-month process before anyone but yourself sees anything that you write. This is true whether you’re working with a publisher or just doing self-publishing. And then people need to go buy the book to get anything out of it. I’ll probably do some more self-published books, but they will be shorter form I think.

Blogging is awesome. Or was awesome. I guess I just got burnt out on blogging. Does it show? πŸ™‚

Earlier this year I was dabbling in woodworking. Set up a basement workshop and started watching videos by this guy Steve Ramsey on his Youtube channel, Woodworking for Mere Mortals. I don’t do so much on the woodworking front now, but I still watch every video he puts out, because he is so freaking awesome.

So I got thinking, maybe I could do something vaguely similar with coding. And thus was born…

The Coding Math Channel!!!

That’s http://www.youtube.com/user/codingmath

I cover a lot of the whys in the first video, but from what I’ve seen, a lot of coders struggle with math. They understand the language they are writing in, but when they are doing a layout or an animation or some kind of effect, they get bogged down in what formulas to use or what numbers to feed in, or what to apply those formulas to. This is something that, for some reason, has always clicked for me. And apparently, once it clicks for me, I’m able to explain in a way that helps it click for other people. I realize I’m tooting my own horn here, but this is what many people have said about my books and talks and blog posts. So I believe them.

Anyway, I figured I’d try to go over some useful math concepts, particularly as they relate to coding – the bits of math that coders need to know and will find useful. And not just cover the math as a disconnected, abstract thing, but use that math in code to demonstrate some kind of effect that you could really use in your own day-to-day programming. The video format is great for being able to draw rough sketches in real time while explaining some concept, and then switching over to demonstrate that concept while coding in real time, then showing the results in the browser – in real time. A flow that is not nearly as smooth in a book or blog post.

As of this writing, I’ve got four videos up there. I held off promoting this until I had at least a bit of useful content up there. I’m hoping to do minimally one video per week, probably publishing it on Monday mornings. I have a nice list of topics to cover, and if there’s any specific things you’d like to see covered, shout it out.

I know the production quality on these isn’t awesome. But I’m a noob here. Learning a bit more about the recording and editing process every time I do one, so bear with me. I think it will improve. πŸ™‚

Also covered in the first episode is the rationale behind using HTML5/JavaScript as a base for these lessons. I’m not counting out the possibility of using other languages in some episodes though, as appropriate.

So, there you have it. Hope you find it useful.

Posted in Educatioon, Technology | 2 Comments

Running Google Chrome on a High DPI Windows Machine

Chrome is my browser of choice. I’ve just moved from an original Surface tablet/laptop to a Lenovo Yoga 2 Pro. Chrome was a bit touchy on the Surface. Or I should say not so touchy. The relatively high DPI screen with the small size caused it to work pretty poorly with touch. I think MS did some updates of their own which seemed to help, but it was still a pain in the neck. I’d be jabbing at the screen like an angry woodpecker sometimes, trying to click on a link.

Now the Yoga 2 Pro has an outrageously high DPI screen: 3200×1800. There’s a bit more physical real estate, but the current version (30) of Chrome was completely unusable on it form a touch screen viewpoint. Literally unusable. (Literally literally, not that new figuratively literally.) Taps on links either just wouldn’t work at all, or would be off by several hundred pixels and activate some link on another part of the page. I assume it’s got something to do with the scaling.

However, after digging around a bit, I found that there’s a setting you can start Chrome with that almost completely, if not completely, fixes this. You just add “–high-dpi-support=1” to the command used to start Chrome. Night and day. Clicks register correctly with the first tap.

Update, makes it much simpler, and only have to do it in one spot.

1. Open Chrome, type “chrome://flags” into the url field.

2. Search for “HiDPI Support”.

3. Change to “Enabled”.

4. Restart Chrome.

5. Ignore the rest of this post! πŸ˜‰

The rest of this post is still valid, but if you do the above, it’s unnecessary.

Now, all you need to know is where to put this flag to make sure that Chrome starts correctly. Basically, you need to find the shortcut that you’re using to start Chrome and add it to that. For this Windows 8 machine, I believe there are two ways I’m starting Chrome: a task bar shortcut and the start screen.

1. Task bar shortcut. If you have a shortcut to Chrome in your task bar, right click on it. You’ll see a quick list and near the bottom will be an item called “Google Chrome”. This is the actual shortcut that you need to change. Right click on that and choose properties, like in the picture below (you can click to expand these if needed):

chrome_properties

That will give you the shortcut properties dialog. In the Target field, you will see the actual path to chrome.exe in quotes. Just add the line –high-dpi-support=1 (note that it’s two hyphens before the word, high) after the quotes like in the next pic:

chrome_properties_2

Click OK to save and the next time you start Chrome with the task bar shortcut, you should be in high DPI mode. Yay.

2. The start page. If you have a Chrome tile on your Windows 8 start page, or you start Chrome by going to the start page and typing Chrome, you’ll need to do the same thing for another shortcut. I believe this one is also the shortcut that is used for apps that open Chrome when it is set at your default browser.Actually, any apps that open a link in a new browser will merely launch Chrome directly, without using a shortcut. However, if you already have a Chrome window open, apps will open links as a new tab in that Window, using the settings it was launched with. I guess the solution is to keep a Chrome window open? At least until this support goes mainstream. The shortcut should be located here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Google Chrome\

In that folder, you should see a Google Chrome shortcut. Right click on it, choose properties and do the same thing as last time.

If you have any other Chrome shortcuts or launchers, you’ll need to do the same thing there.

Hopefully, this will get addressed as some kind of automatic default in a future release of Chrome and this post will be obsolete. It’s also worth noting that Chrome Canary seems to work well on high DPI screens out of the box. So that’s promising for a future regular Chrome version. In the meantime, hope this helps you.

Posted in General | 13 Comments

JavaScript Audio Synthesis Part 3: Making Music

First of all, I am not a musician by any stretch of the imagination. But that fact will become obvious all too soon. But if you’re going to make sound with code, you wind up either making sound effects or music. So let’s start with music. My goal here was to create a simple “tracker” application. You program in notes, it plays those notes back in progression to form a song. Of sorts.

I’m going to keep the song very simple. Mary Had a Little Lamb. It’s a song that you can play every note with one beat, so you don’t have to mess around with different length notes. Here’s a simple version of the song transcribed into notes and rests:

g f e f
g g g –
f f f –
g b b –
g f e f
g g g g
f f g f
e – – –

A quick search on the ‘net gives you the frequency values for the notes b, e, f and g, the only ones you’ll need for this song. Code that into an object:

[php lang=”javascript”]
scale = {
g: 392,
f: 349.23,
e: 329.63,
b: 493.88
}
[/php]

And then you can just code the song as a string.

[php lang=”javascript”]
song = “gfefgg-fff-gbb-gfefggggffgfe—“;
[/php]

Now you can create an AudioContext and an oscillator and set an interval that runs at a certain speed. In the interval callback, get the next note, find its frequency and set the oscillator’s frequency to that value. Like this:

[php lang=”javascript”]
window.onload = function() {

var audio = new window.webkitAudioContext(),
osc = audio.createOscillator(),
position = 0,
scale = {
g: 392,
f: 349.23,
e: 329.63,
b: 493.88
},
song = “gfefgg-fff-gbb-gfefggggffgfe—“;

osc.connect(audio.destination);
osc.start(0);

setInterval(play, 1000 / 4);

function play() {
var note = song.charAt(position),
freq = scale[note];
position += 1;
if(position >= song.length) {
position = 0;
}
if(freq) {
osc.frequency.value = freq;
}
}
};
[/php]

Now this actually works and you should be able to recognize the melody somewhat. But it leaves a lot to be desired. The biggest thing is that there is no separation between notes. You have a single oscillator running and you’re just changing its frequency. This ends up creating a sort of slide between notes rather than distinct notes. And when there’s a rest, well, there is no rest. It just keeps playing the last note.

There are various ways to try to handle this. One would be to call stop() on the oscillator, then change its frequency, then call start() again. But, when you read the documentation, it turns out that start and stop are one time operations on an oscillator. Once you call stop, it’s done. That particular oscillator cannot be restarted. So what to do?

The suggested answer is actually to create a new oscillator for each note. Initially, this sounds like a horrible idea. Create and destroy a new object for every single note in the song??? Well, it turns out that it’s not so bad. There are some frameworks that create a sort of object pool of notes in the background and reuse them. But the downside to that is that every note you create and start continues playing even if you can’t hear it. It’s your choice, and I suppose you could do all sorts of profiling to see which is more performant. But for Mary Had a Little Lamb, I think you’ll be safe to create a new oscillator each time.

To do this, make a new function called createOscillator. This will create an oscillator, specify its frequency and start it. After a given time, it will stop and disconnect that oscillator. You can then get rid of the main osc variable in the code and call the createOscillator function when you want to play a note.

[php lang=”javascript”]
window.onload = function() {

var audio = new window.webkitAudioContext(),
position = 0,
scale = {
g: 392,
f: 349.23,
e: 329.63,
b: 493.88
},
song = “gfefgg-fff-gbb-gfefggggffgfe—“;

setInterval(play, 1000 / 4);

function createOscillator(freq) {
var osc = audio.createOscillator();

osc.frequency.value = freq;
osc.type = “square”;
osc.connect(audio.destination);
osc.start(0);

setTimeout(function() {
osc.stop(0);
osc.disconnect(audio.destination);
}, 1000 / 4)
}

function play() {
var note = song.charAt(position),
freq = scale[note];
position += 1;
if(position >= song.length) {
position = 0;
}
if(freq) {
createOscillator(freq);
}
}
};
[/php]

This sounds better already. Each note is distinct, and when there is a rest, no note plays. But you can do even better.

The notes are just flat tones at this point. You can improve this by giving them a quick and dirty sound envelope. In real life, a sound doesn’t usually just start at full volume and cut out to silence when its time is up. The volume usually ramps up a bit first (the attack) and fades out quickly or slowly (the decay). Actually, sound envelopes can be much more complex than this (http://en.wikipedia.org/wiki/ADSR_envelope#ADSR_envelope) but a simple attack and decay to 0 will do fine for now and give the notes a much better sound.

As a sound envelope controls the volume of a sound, you’ll need to create a gain node. Do this inside the createOscillator function:

[php lang=”javascript”]
function createOscillator(freq) {
var attack = 10,
decay = 250,
gain = audio.createGain(),
osc = audio.createOscillator();

[/php]

The attack and decay values there are in milliseconds. This means that the sound will ramp up from 0 to full volume in 0.01 seconds and then back down to 0 in .25 seconds.

Next, the gain node will need to go between the oscillator’s output and the destination in order to control the volume of that oscillator.

[php lang=”javascript”]
gain.connect(audio.destination);
gain.gain.setValueAtTime(0, audio.currentTime);
gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000);
gain.gain.linearRampToValueAtTime(0, audio.currentTime + decay / 1000);

[/php]

First you set the gain to 0, which in essence sets the volume to 0. You do this with the setValueAtTime method, passing in the current time from the AudioContext object. In other words, set the volume to 0, NOW.

Then you use linearRampToValueAtTime to set the attack and decay. This says go from whatever value you are currently at and interpolate to this new value so that you arrive there at the specified time. Note that the values you pass in here are in seconds, so you’ll need to divide by 1000 when using millisecond values.

Finally, you connect the oscillator to the gain, set the frequency and start it. And of course, when you clean up, you’ll need to disconnect everything as well.

[php lang=”javascript”]
osc.frequency.value = freq;
osc.type = “square”;
osc.connect(gain);
osc.start(0);

setTimeout(function() {
osc.stop(0);
osc.disconnect(gain);
gain.disconnect(audio.destination);
}, decay)
}
[/php]

The final code is below:

[php lang=”javascript”]
window.onload = function() {

var audio = new window.webkitAudioContext(),
position = 0,
scale = {
g: 392,
f: 349.23,
e: 329.63,
b: 493.88
},
song = “gfefgg-fff-gbb-gfefggggffgfe—“;

setInterval(play, 1000 / 4);

function createOscillator(freq) {
var attack = 10,
decay = 250,
gain = audio.createGain(),
osc = audio.createOscillator();

gain.connect(audio.destination);
gain.gain.setValueAtTime(0, audio.currentTime);
gain.gain.linearRampToValueAtTime(1, audio.currentTime + attack / 1000);
gain.gain.linearRampToValueAtTime(0, audio.currentTime + decay / 1000);

osc.frequency.value = freq;
osc.type = “square”;
osc.connect(gain);
osc.start(0);

setTimeout(function() {
osc.stop(0);
osc.disconnect(gain);
gain.disconnect(audio.destination);
}, decay)
}

function play() {
var note = song.charAt(position),
freq = scale[note];
position += 1;
if(position >= song.length) {
position = 0;
}
if(freq) {
createOscillator(freq);
}
}
};
[/php]

Now the notes have a more bell-like sound. It’s not awesome, but it’s a whole lot better. Mess around with trying to create different envelopes to see how that changes the sound. Code in your own song strings too. Don’t forget to add any additional note frequencies that you might use. You might even want to do something with allowing more than one-beat notes, though that starts to get a bit more complex.

Anyway, this is pretty rough and dirty code. A whole lot that could be improved upon here, but it’s good for demonstration purposes and hopefully gives you a better understanding of the underlying fundamentals than a more complex structure would. Have fun with it.

Posted in JavaScript | 3 Comments