roam/20210219114633-digital_audio_processing.org
2021-07-29 18:51:25 -04:00

71 lines
1.6 KiB
Org Mode

:PROPERTIES:
:ID: 4d9e7aa6-1212-4487-84e7-5f9ac8205585
:END:
#+title: Digital Audio Processing
Analysis and manipulation of [[id:472c309f-d50b-4d3b-86cf-1af7c93db0b5][PCM Audio]].
* Sine Wave
#+name: sine-wave
#+begin_src python :exports code :results silent
import numpy as np
samplerate = 44100
frequency = 440
samples = 44100
x = np.arange(samples)
return 100 * np.sin(2 * np.pi * frequency * x / samplerate)
#+end_src
#+begin_src python :exports results :results file :noweb yes
from matplotlib import pyplot as plt
def wave():
<<sine-wave>>
plt.plot(wave()[:100])
plt.title("Sine Wave")
plt.savefig("dap-sinewave.png")
return "dap-sinewave.png"
#+end_src
#+RESULTS:
[[file:dap-sinewave.png]]
* Getting volume with audioop
The power of an audio signal is computed using the *root mean square* of the
fragment:
\begin{equation}
{\displaystyle x_{\text{RMS}}={\sqrt {{\frac {1}{n}}\left(x_{1}^{2}+x_{2}^{2}+\cdots +x_{n}^{2}\right)}}.}
\end{equation}
#+begin_src python :noweb yes :results file
import audioop
import struct
from matplotlib import pyplot as plt
def sinewave():
<<sine-wave>>
wave = sinewave()
chunksize = 441
chunks = [wave[i : i + chunksize] for i in range(0, len(wave), chunksize)]
raw_chunks = [struct.pack(f"{chunksize}h", *map(int, chunk)) for chunk in chunks]
plt.plot(
[audioop.max(c, 2) for c in raw_chunks],
label="peak")
plt.plot(
[audioop.rms(c, 2) for c in raw_chunks],
label="rms")
plt.legend()
plt.title("Volume")
plt.savefig("dap-volume.png")
return "dap-volume.png"
#+end_src
#+RESULTS:
[[file:dap-volume.png]]