So after creating the oscillators and fixing the sound, it's time to actually put them to work by playing a simple tune. To start with, I'll just do a simple scale starting at C and ending at C one octave above.
First thing's first: I need to know the frequencies of the notes. To spare you the details, here they are:
C4: 428
D4: 480
E4: 538
F4: 570
G4: 640
A4: 720
B4: 808
C5: 856
To make these simpler to use, I created an enum for notes. Each value contains the frequency needed to play the specified note.
Now, to actually play these notes, I'll need to make some changes to AudioPlayer.kt. Previously, it was always playing the same frequency. Now, I need to specify the note, duration, volume, and panning.
Here's how I changed things: First, I made separate functions for setting up and tearing down the source data line. I now call these from main.kt. Next, I refactor the playAudio function and rename it to playNote. It accepts the note enum, volume, panning, and duration of the note.
Rendering the audio and putting it into the source data line works more or less the same as before. It ends up looking like this.
I immediately noticed a problem. When I was testing, I tried playing a note at frequency 381. It sounded way off. Looking at the oscillator math, I found out why: It was not properly calculating the length of the period, and the period was slightly shorter than my equation was expecting.
![]() |
It's a little hard to see in this image, but look at the wave as it approaches 0 from below at the middle and near the end of the graph. |
It's a subtle error, but it's enough to completely throw off the sound of the sine wave. I needed to change my calculation for the graph. The error was in the getXValue function in the base Oscillator class. It turns out I already had the number I needed to fix it, I just needed to change my math slightly.
After doing this, I was able to play a simple scale. Look at this commit to see more.
The oscillator fix made my other oscillators sound better, too. That being said, the volume seems to vary a bit in the sinewave oscillator. So I think I need to find out why. The sawtooth and triangle waves sound pretty good now, but the square wave sounds off still. I'll look into that.
Comments
Post a Comment