BLOG

Notes from the KAYAC hyper-casual team

Dynamic Waveform Generation That Plays Sound Without an AudioClip

Takashi Hirayama

YouTube: 6VPaj8cEoWw

Hello. I'm Hirayama from the Technology Department.

Today I tried creating audio waveforms at runtime in Unity and playing them. Sadly, this is 99.9% hobby. Music and sound effects are normally made in advance and played back, and I doubt you'll ever really need to generate a waveform on the CPU while playing it.

The API I'm using is really meant for applying effects to a waveform; you can do things like adding an echo-like effect to the sound coming out of an AudioClip. But if one of the built-in filters does the job, it probably uses less power and has less impact on performance, so I'd like to find a good use for this that the filters can't cover.

I also came across a post about analyzing the waveform to make a character lip-sync to it. I see: rather than changing or generating sound, you can also grab the waveform to do something in sync with the sound.

Sample code

The code is on GitHub in the form of a sample project. I'd have liked to provide a WebGL build, but unfortunately the technique used here doesn't work in WebGL, so you'll have to download the project and run it in the editor. Run it and press any of the keys "awsedftgyhujkolp" to play a sound.

MonoBehaviour.OnAudioFilterRead

What I use is MonoBehaviour.OnAudioFilterRead(). If you attach a component that implements OnAudioFilterRead to a GameObject with an AudioSource, you can apply your own filter to the sound coming out of that AudioSource.

For example, something like this halves the signal:

void OnAudioFilterRead(float[] data, int channels)
{
    for (int i = 0; i < sampleCount; i++)
    {
        data[i] = data[i] * 0.5f;
    }
}

Now, when would you actually use this in a product? As the official manual says, reducing high frequencies (LowPass), reducing low frequencies (HighPass), adding echo (Echo), distorting (Distortion), adding reverberation (Reverb) and adding chorus (Chorus) are all provided as standard. If you want to make things uniformly louder or quieter, you should just adjust the volume, and it's hard to think of a calculation worth running on the CPU over 40,000 or 80,000 floats of waveform data per second.

Implementation caveats

This function is called on a separate thread, so you can't use UnityEngine functions. That said, Mathf was fine. It seems you can make sine waves with Sin and Cos.

From here on, it's just a hobby

Waveform generation

This sample is a sort of piano. The computer keyboard stands in for piano keys, and pressing a key plays a sound.

Under the hood, there's a spring-damper for each key, and I sum the waveforms they generate, playing 88 sine waves from a single AudioSource.

struct Oscillator
{
    public void Attack(float strength)
    {
        var pulse = strength * Mathf.Sqrt(Stiffness);
        velocity += pulse;
    }
    public float Update(float deltaTime)
    {
        velocity -= velocity * Damping * deltaTime;
        velocity -= position * Stiffness * deltaTime;
        position += velocity * deltaTime;
        return position;
    }
    float position;
    float velocity;
    public float Stiffness { set; private get; }
    public float Damping { set; private get; }
}

The harmonic oscillator is represented by this Oscillator type; it holds a position and a velocity and is Euler-integrated in Update().

In an article I wrote before, I showed that a spring-damper can represent trigonometric functions, and this is an application of that. You can compute trigonometric functions without Sin() or Cos().

Then I stuff the sum of all the sine waves into the array passed in as the argument of OnAudioFilterRead().

void OnAudioFilterRead(float[] data, int channels)
{
    int sampleCount = data.Length / channels;
    for (int i = 0; i < sampleCount; i++) // for as many samples as needed
    {
        float v = UpdateOsccilators(); // update the integration of all oscillators
        for (int c = 0; c < channels; c++) // copy for each channel
        {
            data[(i * channels) + c] = v;
        }
    }
}

float UpdateOsccilators()
{
    var v = 0f;
    for (int i = 0; i < oscillators.Length; i++)
    {
        v += oscillators[i].Update(deltaTime);
    }
    return v;
}

There are 88 spring-dampers, one for each key on a piano, and in stereo it outputs an array of 44100*2=88200 elements per second, so it's updating spring-dampers 88200*88=7761600 times per second. What a terrible implementation. Besides, there are only 16 keys you can actually press, so having 88 is a complete waste. Oh well, it's just for fun.

Spring-damper parameters

Each spring-damper corresponds to a piano key, so its frequency is fixed.

For a 100Hz sound, for example, the parameters need to make it oscillate 100 times per second. A spring-damper has two parameters, the spring constant (Stiffness) and the damping constant (Damping), and the one related to frequency is the spring constant. Set it right, and when you give the spring-damper's velocity a pulse, it oscillates at the frequency you want.

Now, if you ignore damping, a spring-damper becomes a harmonic oscillator. Ignore phase too, because it's a hassle, and use only sin, and the code that computes the harmonic oscillator's position is this:

p = sin(sqrt(k) * t);

k is the spring constant. Out of laziness, I've set both amplitude and mass to 1.

When sqrt(k) * t increases by 2pi, the sine goes around once, so the number of revolutions per second is sqrt(k) / (2 * pi). Revolutions per second = the frequency of the sound, so if this is 100Hz, k = (2 * pi * 100)^2. So once you know each key's frequency, you can find the spring constant.

Now, the lowest key on a piano is A. It's 4 octaves below the 440Hz A used for time-signal beeps. Each octave down halves the frequency, so dividing by 2 to the 4th = 16 gives 27.5Hz. After that you just "multiply by the 12th root of 2 for each semitone up", and you're done.

var step = Mathf.Pow(2f, 1f / 12f); // 12th root of 2
var f = 440f / 16f;
for (int i = 0; i < oscillators.Length; i++)
{
    var w = f * 2f * Mathf.PI;
    var stiffness = w * w;
    oscillators[i].Stiffness = stiffness;
    f *= step;
}

The Nth root is the 1/Nth power, so you can get it with Pow. If I were doing this properly, I'd avoid accumulating multiplications to prevent rounding errors.

Pulse

When a key is struck, the spring-damper's velocity is changed instantaneously, like a hammer striking a piano string. How much should it change to oscillate at the desired amplitude?

You can tell by differentiating the harmonic oscillator's equation.

v = sqrt(k) * -cos(sqrt(k) * t);

It's multiplied by sqrt(k), so the velocity oscillates from -sqrt(k) to +sqrt(k). If you want it to oscillate with an amplitude of 0.5, you just give it a velocity of sqrt(k)*0.5.

public void Attack(float strength)
{
    var pulse = strength * Mathf.Sqrt(Stiffness);
    velocity += pulse;
}

Note that at the same amplitude, low sounds are harder to hear, so they don't feel equally loud. For more on this, the AIST website should be a useful reference. A 30Hz sound comes across at only about 1/100 the loudness of a 120Hz sound, so it's effectively inaudible. On a piano it booms, but what you're hearing is almost entirely overtones. I think if I added overtones to this app too, it would sound like that.

What's next

It's just for fun, so there's no "next" really, but there are a few more things I'd like to do if I have time.

  • Synthesizing timbres
  • Wobble
  • Smartphone support
  • Resonance

Synthesizing timbres

To change the timbre, you just use a waveform other than a sine wave, but "obviously electronic" sounds like square waves and triangle waves are too retro. Using multiple spring-dampers for one sound lets you synthesize a timbre, so it would be fun to turn this into a toy for playing around with that.

Wobble

It would be nice to be able to add expression to the sound with a drag or some other gesture. On a smartphone, bringing in the accelerometer sounds interesting. Changing the spring constant slightly every frame makes the pitch wobble.

Smartphone support

With the current UI you can't do anything without a keyboard, so I'd like to make a piano-key UI and get it running on smartphones. It's just a toy, so I couldn't justify the time, and even if I posted a smartphone build here I doubt anyone would install it, so I didn't go that far this time. If only OnAudioFilterRead worked in WebGL...

Resonance

Put two strings of the same length side by side and set one vibrating, and the other starts vibrating too. If each string picked up vibrations from the other strings and vibrated in turn, the sounds would intertwine in complex ways, which sounds interesting. But the amount of computation would explode, so I'd want to do it with shaders. I'd like to see whether compute shaders could be used for it.

In closing

I'm an amateur at game sound processing, but I've long felt it could use more dynamic computation. Just streaming prerecorded sound offers little interactivity and gets boring quickly. Applying effects is one effective approach, but I wish we could go further and do something like "the music's mood changes with the scene without any break in the music at all" (there are works that do this, so it's nothing new).

Maybe it would even be fun to try making a game using only dynamic synthesis of sine waves. Though it probably wouldn't sell.

Bonus

I changed naming conventions for this one. In our company's games division, the common conventions are

  • private variables start with _ and are camelCase
  • property names are camelCase, like Unity's

but this time I went with

  • private variables are camelCase without _
  • property names are PascalCase, following the C# standard

I decided that for code published to the world, it's better to follow Microsoft's official documentation. That document says nothing about private, but in Microsoft's HoloLens sample private was camelCase, so I followed that.

But I'm not used to being unable to tell local variables from private fields, and I sometimes have to write this, so I may get fed up and switch back.