Next lesson playing in 5 seconds

  • Overview
  • Transcript

2.5 Disposable Oscillators

Web Audio oscillators stop working after they've been used. In this lesson I'll explain why and show you how to plan your software to take that into account.

2.5 Disposable Oscillators

Okay, in the last lesson, we had an issue when playing a note more than once. The reason for this is down to the way in which the way body PI was designed. Notes such as oscillators are designed to be cheap to create and throw away after use. Think of it as some sort of weird audio firework. The reason for this is that browsers don't have to hold onto oscillators, or notes, that it thinks you may or may not need at some point in the future. And allows it to do its garbage collection much more efficiently. All of this means, that when we're creating our synth, we just have to create an oscillator, and play it on every key press. Don't worry about the performance of this. The browser is more than capable of doing this. Meaning the note will play instantaneously when pressing a key. Okay, let's go back to our editor and move things around a little. Let's take everything to do with creating an oscillator and put it inside our key down function. So that includes creating the oscillator as well as connecting it to the volume note. So this means that the oscillator will be created and played on key down, but our osc variable is closed inside this function here. Meaning that key up will have no knowledge about it. A way we can work around this is to first create an object outside the scope of these two functions, up here. Let's call it oscillators. Then in our key down function, we simply say, oscillators[note]=osc. So what this is doing, is using the name of the note passed into our function, as a key enter object. Now our key up function also passes through note and frequency values. This means that we can access the oscillator we just created by referencing it in the same way we added it to our object. Oscillators, note. We should also disconnect our oscillator as we don't need it anymore. Let's quickly recap what we've done here before try it out. We've created an oscillator object in our global scope. We've added a reference to our oscillator by using the note name of the key pressed. We then use that reference to tell oscillator to stop and to disconnect it from our game node. Okay, let's head over to the browser to see it in action. [MUSIC] Amazing, I'll leave you for a minute to have some fun with your creation.

Back to the top