# Making Music with Math ### A Guide to Synthesizing Sounds with the Wave Equation When you pluck a guitar string or play a key on a piano, the sound is created by a vibrating string. The [wave equation](https://en.wikipedia.org/wiki/Wave_equation) tells us exactly how an idealized string will vibrate at every moment in time after the string is released. Using this equation, it's possible to simulate the motion of a vibrating string and extract musical sounds from this motion. In this post, we'll take a stab at doing this. ## The Wave Equation Let $y(x,t)$ represent the string's height, plotted as a function of distance $x$ along the string, at any moment in time $t$. You can think of $y(x, t)$ as a graph of the string's motion. As we increment $t$, the graph becomes an animation. The wave equation requires that every point on this graph must satisfy $$ \frac{\partial^2 y}{\partial t^2} = c^2 \frac{\partial^2 y}{\partial x^2} $$ Or, more concisely, $$\ddot{y} = c^2 y''$$ where $c$ is the speed of the traveling wave moving along the string. In words, this says that the vertical acceleration of every point on the string is proportional to the curvature at that point. In this picture, we're ignoring both energy loss from friction as well as any stiffness in the string. We also need the string to be fixed at its ends, i.e. $$ y(0,t) = 0 $$ $$ y(L,t) = 0 $$ where $L$ is the string's length. The solutions to this set of requirements are $$ y_n = \sin (k_n x) \big( A_n \cos(\omega_n t) + B_n \sin(\omega_n t) \big)$$ where $k_n = \frac{n \pi}{L}$, $\omega_n = c \frac{n \pi}{L}$, $n = 1,f2,3,...$, and $A_n$ and $B_n$ are coefficients to be determined. With a little calculus, you can verify that these solutions obey the wave equation. You can also verify that the string is fixed at the ends, as required. These solutions ($y_n$) are known as the *normal modes* of the string. I like to think of these as the simplest possible ways in which a string can vibrate. Let's visualize the first few of these normal modes. As we increase $n$, the string oscillates more rapidly. The frequency of vibration of each normal mode $f_n$ is related to $\omega_n$ by $f_n = \frac{\omega_n}{2 \pi}$. Plugging in $\omega_n = c \frac{n \pi}{L}$, we find that $f_n = n \frac{c}{2 L} = n f$, where $f$ is the *fundamental frequency* of the string. It's worth pausing to appreciate what just happened. We asked the wave equation to make sure that the ends of the strings can't move. In response, the wave equation came back and told us that the string can *only* vibrate at a very specific set of frequencies. In the case of the ideal string, these allowable frequencies are integer multiples of a fundamental frequency (f, 2f, 3f, ...). Together, these frequencies are known as the *harmonics* of the string. ## Mixing Modes of Vibration The wave equation is a **linear equation**, which means that if $y_1$ is a solution and $y_2$ is a solution, then any combination of the form $a y_1 + b y_2$ is also a solution to the wave equation. The key point here is that *mixtures of solutions to the wave equation are also themselves solutions*. So we can obtain more complex patterns of string vibration by mixing together different normal modes. Here, try it out for yourself. When you're done mixing, turn up the speed slider to unfreeze the wave, and watch its ensuing motion. By dragging these sliders, you're mixing different proportions of the first 6 normal modes (we're adjusting the $A_n$ coefficients here, the $B_n$ coefficients are set to zero). Each mixture is a different, perfectly valid solution to the wave equation. A somewhat amazing fact is that essentially any string shape can be expressed as a sum of different normal modes. So, the most general type of string vibration is $$ \begin{aligned} y &= y_1 + y_2 + y_3 + \ldots \\ &= \sum_{n=1}^\infty y_n \end{aligned} $$ Or, $$ y = \sum_{n=1}^\infty \sin (k_n x) \big( A_n \cos(\omega_n t) + B_n \sin(\omega_n t) \big) $$ where $k_n = \frac{n \pi}{L}$, $\omega_n = c \frac{n \pi}{L}$, and $c$ is the speed of the travelling wave in the string. Solving the wave equation in a particular situation amounts to working out the coefficients $A_n$ and $B_n$. Once we know these coefficients, we can plug them into the equation above to obtain a graph of every point on the string for all time. ## Fourier's Trick But how do we find these coefficients? To do this, we need to know something more about the string. In particular, we need to know the **initial position** and the **initial velocity** of the string, represented by $y(x,0)$ and $\dot{y}(x,0)$. Going back to the equation for $y(x,t)$, we can plug in $t=0$ to find that $$ y(x,0) = \sum_{n=1}^\infty A_n \sin (\frac{n \pi x}{L}) $$ Similarly, if we take a time derivative before plugging in $t=0$, we find that $$ \dot{y}(x,0) = \sum_{n=1}^\infty B_n \omega_n \sin (\frac{n \pi x}{L}) $$ To solve these for $A_n$ and $B_n$, we can use the classic [Fourier trick](https://books.google.com/books?id=Kh4xDwAAQBAJ&pg=PA134&dq=Fourier%27s+trick+griffiths&hl=en&newbks=1&newbks_redir=0&sa=X&ved=2ahUKEwib2eD80_blAhWLjFkKHY8YB9oQ6AEwAHoECAQQAg#v=onepage&q&f=false) of multiplying both sides of the equation by $ \sin (\frac{m \pi x}{L}) $ and integrating over x. Doing so, we arrive at equations for $A_n$ and $B_n$. $$ A_n = \frac{2}{L} \int_{0}^{L} y(x,0) \sin (\frac{n \pi x}{L}) dx$$ $$B_n = \frac{2}{\omega_n L} \int_{0}^{L} \dot{y}(x,0) \sin (\frac{n \pi x}{L}) dx$$ This solves the ideal string. Notice that $A_n$ only depends on the initial position of the string, while $B_n$ only depends on the initial velocity. If we plug in formulas for $y(x,0)$ and $\dot{y}(x,0)$ into these integrals, we obtain $A_n$ and $B_n$. Then, $$ y(x,t) = \sum_{n=1}^\infty \sin (k_n x) \big( A_n \cos(\omega_n t) + B_n \sin(\omega_n t) \big) $$ tells us the subsequent motion of the string. To summarize, if we know *exactly* how the string started (i.e. its initial position and its initial velocity), then we can calculate everything about its subsequent motion. ## The Plucked String When you play a note on a guitar, you pluck the string and give it an initial shape. For a purely plucked string, the initial velocity of the string is zero. Since $\dot{y}(x,0) = 0$, this tells us that $B_n = 0$. The solution for the ideal plucked string reduces to $$ y = \sum_{n=1}^{\infty} A_n \sin (k_n x) \cos(\omega_n t) $$ where $k_n = \frac{n \pi}{L}$ and $\omega_n = c \frac{n \pi}{L}$. So we just need to find $A_n$. Say that the string is plucked at a length $l$ along the string, with an initially triangular string shape. $$ y(x,0) = \begin{cases} h \frac{x}{l} & \text{if } x \leq l \\ h \frac{L - x}{L - l} & \text{if } l < x \leq L \end{cases} $$ Here's what this function for the plucked guitar string shape looks like. We can plug this function into to our integral for $A_n$, and use a tool like Wolfram Alpha to solve the integral. The [solution](https://www.wolframalpha.com/input/?i=%282%2FL%29*%28Integrate%5Bsin%28n+pi+x+%2F+L%29+*+h*x%2Fl%2C%7Bx%2C0%2Cl%7D%5D+%2B+Integrate%5Bsin%28n+pi+x+%2F+L%29+*+h*%281-x%2FL%29*%28L%2F%28L-l%29%29%2C%7Bx%2Cl%2CL%7D%5D%29) is $$ A_n = \frac{2}{\pi^2} \frac{h}{\frac{l}{L} (1 - \frac{l}{L})} \frac{1}{n^2} \sin(\frac{n \pi l}{L})$$ Let's animate this solution for the first $N$ terms in the sum. $$ y(x,t) = \sum_{n=1}^{N} A_n \sin (k_n x) \cos(\omega_n t)$$ The animation above shows the motion of the string following the initial pluck (with $h$ set to $1$). As you add more terms to the sum, the animation becomes an increasingly good approximation of the string's motion. You can compare this animation to [slow-motion video footage](https://www.youtube.com/watch?v=3ATVOTJfkg8) of an actual plucked guitar string (or to [this footage](https://www.youtube.com/watch?v=_X72on6CSL0) of a more idealized string). The next step is to extract an audio waveform from this string motion. For the waveform $w(t)$, we want only the time-dependent part of the string motion. $$ w(t) = \sum_{n=1}^{N} A_n \cos(\omega_n t)$$ The interactive above shows you the waveform for the plucked string. Notice how it changes depending on where you pluck the string. To make sound with this waveform, we first need to do a couple of things. - Rewrite $\omega_n$ in terms of the fundamental frequency of the tone, so $\omega_n = 2 \pi n f$. - A real plucked string has a sound that fades. To model this, we need the string to dissipate energy. One way to do this is to ensure that each sine or cosine function decays exponentially, with a decay time $\tau_n$ that depends on its frequency (higher frequencies fade faster than lower ones). Following [this reference](http://large.stanford.edu/courses/2007/ph210/pelc2/), we can choose $\tau_n = \frac{\tau}{n}$ where $\tau$ is a characteristic fade time (in seconds). Making these changes, we end up with the following waveform. $$ w(t) = \sum_{n=1}^{N} A_n \cos(2 \pi n f t) e ^{ - n t / \tau }$$ Here's what this sounds like.
Fundamental Frequency = {{freq}}
  
Notice that as the pluck position moves towards the edge of the string, the sound becomes brighter. ## The Struck String When you play a piano note, the string is struck with a hammer. So it's worth thinking about what happens when an ideal string is struck. In a purely struck string, the string starts at rest, but with a non-zero initial velocity. Since $y(x,0) = 0$, this implies that $A_n = 0$. So the solution for the ideal struck string reduces to $$ y = \sum_{n=1}^{\infty} B_n \sin (k_n x) \sin(\omega_n t) $$ where $k_n = \frac{n \pi}{L}$ and $\omega_n = c \frac{n \pi}{L}$. To solve for $B_n$, we need to use the fact that we know the initial velocity $\dot{y}(x,0)$. Suppose that we strike the string with a velocity impulse concentrated at a point located a distance $l$ along the string. This would be like striking the string with the edge of a knife. We can model this velocity distribution as a delta function, which you can think of as striking the string with an infinitely thin hammer. $$ \dot{y}(x,0) = v L \delta (x-l) $$ Here $v$ is the speed with which the string is struck, and the delta function $\delta (x-l)$ has the property that $ \int_{0}^{L} f(x) \delta (x - l) dx = f(l) $ if $0 \leq l \leq L$. (The extra factor of L is there to make the units work out.) Performing the integral for $B_n$, we arrive at the solution $$ B_n = \frac{2 v}{\omega_n} \sin (\frac{n \pi l}{L}) $$ Substituting $\omega_n = \frac{n \pi c}{L}$, we see that $$ B_n = \frac{2}{\pi} \frac{v L}{c} \frac{1}{n} \sin (\frac{n \pi l}{L}) $$ Let's animate this solution for the first $N$ terms in the sum. $$ y(x,t) = \sum_{n=1}^{N} B_n \sin (k_n x) \sin(\omega_n t)$$ If you strike the string near one of its ends, you can watch the pulse propagating along the string, and reflecting off the ends! Once again, let's visualize the waveform. We can obtain the waveform by throwing away the spatial part of the string motion, and only holding on to the time-dependent part. $$ w(t) = \sum_{n=1}^{N} B_n \sin(\omega_n t) $$ Here's what this sounds like, after adding in an exponential fade.
Fundamental Frequency = {{freq}}
  
The struck string has a noticeably harsher sound than the plucked string. This is because it has more energy in higher harmonics. The amplitudes corresponding to the $n^{\text{th}}$ harmonic in the plucked string fall off as $\frac{1}{n^2}$, but in the struck string they fall off as $\frac{1}{n}$. Unfortunately, this doesn't sound very piano-like. We can try and see what happens if we replace the infinitely narrow hammer strike with a finite-width hammer. ## Varying the Strike Width In this case, imagine that the initial velocity of the string is $$ \dot{y}(x,0) = \begin{cases} v & \text{if } l - \frac{\delta}{2} \leq x \leq l + \frac{\delta}{2} \\ 0 & \text{otherwise} \end{cases} $$ This is visualized in the interactive below. Note that this is a graph of the initial *velocity* of the string, not its initial position. Plugging this into our equation for $B_n$, we find that in the case of a finite-width hammer, the coefficients are $$ B_n = \frac{4 v}{n \pi \omega_n} \sin(\frac{n \pi \delta}{2L}) \sin(\frac{n \pi l}{L}) $$ Substituting $\omega_n = \frac{n \pi c}{L}$, we find that $$ B_n = \frac{4}{\pi^2} \frac{v L}{c} \sin(\frac{n \pi \delta}{2L}) \frac{1}{n^2} \sin(\frac{n \pi l}{L}) $$ Here's what the string motion looks like when struck by this kind of a hammer. When the hammer is very thin, the resulting motion is reminiscent of the delta function impulse that we saw above. When we broaden the hammer, the pulse becomes wider and is more smoothed out in appearance. If you set the strike position to be exactly in the middle and the hammer width to about 0.1, the motion you see resembles that in this [slow-motion video](https://www.youtube.com/watch?v=9O3VEXzuOKI) of a struck string. The waveform for this string motion is shown below. Here's what this sounds like, after adding in an exponential fade.
Fundamental Frequency = {{freq}}
  
For a thin hammer strike, the sound has a harsh attack and sounds like the earlier struck string (where we used an infinitely thin hammer). However, as we increase the hammer size, the sound becomes more like the plucked string. In either case, we can hear that the sound isn't particularly piano-like. In reality, the interaction between a piano hammer and the string is more complicated than a simple 'kick' of velocity. In more realistic physics-based piano models, the interaction between the piano and the string is considered more carefully. ## The Bowed String Say we bow the string, as in a violin. The actual motion of a bowed string is fairly complex, but we can take a stab at a simplified model. The physicist Helmholtz observed that when a violin string is bowed, the speed of the bowed point on the string matches the speed of the bow. Let's bow our ideal string. We'll assume that the string is at rest, and is given a velocity profile that rises linearly from zero at the ends to peaking at the location of the bow. This is similar to the case of the plucked string, except now we are describing the inital *velocity* and not the position of the string. $$ \dot{y}(x,0) = \begin{cases} v \frac{x}{l} & \text{if } x \leq l \\ v \frac{L - x}{L - l} & \text{if } l < x \leq L \end{cases} $$ Plugging this in to our integral for $B_n$, we obtain $$ B_n = \frac{1}{\pi^2} \frac{2 v}{\omega_n \frac{l}{L} (1 - \frac{l}{L})} \frac{1}{n^2} \sin(\frac{n \pi l}{L})$$ Substituting $\omega_n = \frac{n \pi c}{L}$, we arrive at $$ B_n = \frac{2}{\pi^3} \frac{v L}{c} \frac{1}{\frac{l}{L} (1 - \frac{l}{L})} \frac{1}{n^3} \sin(\frac{n \pi l}{L})$$ Here's an animation of the resulting string motion, with $v = 1$. Say you bow the string near one of the ends. The red dot shows the point where the bow touches the string. Notice how it moves. You'll see that it moves slowly in one direction, and then suddenly snaps back in the opposite direction. This is the characteristic **slip-stick motion** of a bowed violin string, illustrated in the animation at [this link](https://newt.phys.unsw.edu.au/jw/torsional.html). The slower motion in one direction occurs when the string sticks to the bow, and the sudden motion in the other direction occurs when the string slips away from the bow. You can compare this motion to [slow-motion video footage](https://www.youtube.com/watch?v=6JeyiM0YNo4) of a bowed violin string. (In the video, the string tension has been lowered to greatly exaggerate the string motion). Here's the waveform for this sound. Here's what this sounds like, after adding in an exponential fade.
Fundamental Frequency = {{freq}}
  
In this discussion, we've only considered how the string vibrates. In any real instrument, the string vibration doesn't directly produce sound. Without its body to amplify the sound, a string instrument would be inaudibly quiet. This is because strings by themselves can't effectively transfer their energy to air molecules. In the case of the piano, the string is coupled to a soundboard via the piano bridge. The vibration of this soundboard produces much of the audible sound. In the case of a violin or guitar, it's coupled to the resonating body of the instrument, also via the bridge. This amplifies and filters the string sound, and so the resulting waveform and sound is greatly altered from the one that we obtained directly from the string's vibration. So if you're seriously attempting to synthesize the sound of a musical instrument, you'll also need to account for the effect of the instrument's body on the sound. However, it's still interesting to see how far we can go just from the wave equation of an ideal string, by appplying the appropriate initial conditions. ## References The source code for this article is available on [Github](https://github.com/aatishb/stringmath). The animations are created using the [p5.js](https://p5js.org/) library, and the interaction uses [Vue.js](https://vuejs.org/).