The aim of this short notebook is to show how to use NumPy and SciPy to play with spectral audio signal analysis (and synthesis).

Lots of prior knowledge is assumed, and here no *signal theory* (nor its mathematical details) will be discussed. The reader interested a more formal discussion is invited to read, for example: "Spectral Audio Signal Processing" by Julius O. Smith III that is a precise and deep, yet manageable, introduction to the topic.

For the reader less inclined in formal details (heaven forbid that the others will read the following sentence) suffices it to say that any (periodic) signal can be obtained as a superposition of *sine* waves (with suitable frequencies and amplitures).

The roadmap of what we'll be doing is:

- take a real signal (a
*violin*and a*flute*sample), - perform a
*spectral analysis*, - determine some of the
*frequencies*having the strongest*amplitudes*in such spectrum, - "reconstruct" a signal using just a few
*sine*waves, - play the orignal, and reconstructed signal.

As you'll see, beside what theory guarantees, this actually works and very few waves are enough to approximate the *timbre* of a musical instrument.

The source notebook is available on GitHub (under GPL v3), feel free to use issues to point out errors, or to fork it to suggest edits.

A special thanks to the friend and colleague Federico Pedersini for tolerating my endless discussion and my musings.

In [1]:

```
%matplotlib inline
from IPython.display import Audio
import librosa
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
plt.rcParams['figure.figsize'] = 8, 4
plt.style.use('ggplot')
```

We'll fix the sampling rate once and for all to 8000Hz, that is sufficient for our audio purposes, yet low enough to reduce the number of samples involved in the following computations.

In [2]:

```
RATE = 8000
```

We define a couple of helper functions, to *load* the samples in a WAV file and to generate a *sine* wave of given *frequency* and *duration* (given the sampling `RATE`

defined above).

In [3]:

```
def load_signal_wav(name):
signal, _ = librosa.load(name + '.wav', sr = RATE, mono = True)
return signal
```

In [4]:

```
def sine_wave(freq, duration):
return np.sin(np.arange(0, duration, 1 / RATE) * freq * 2 * np.pi)
```

Let's check we've done a good job by playing a couple of seconds of a "pure A", that is a sine wave at 440hz

In [5]:

```
samples_sine = sine_wave(440, 2)
Audio(samples_sine, rate = RATE)
```

当前网页内容, 由 大妈 ZoomQuiet 使用工具: ScrapBook :: Firefox Extension 人工从互联网中收集并分享;

内容版权归原作者所有;

本人对内容的有效性/合法性不承担任何强制性责任.

若有不妥, 欢迎评注提醒:

或是邮件反馈可也:

askdama[AT]googlegroups.com

订阅 substack 体验古早写作:

点击注册~> 获得

关注公众号, 持续获得相关各种嗯哼:

关于 ~ DebugUself with DAMA ;-)

粤ICP备18025058号-1

公安备案号: 44049002000656 ...::