roam/20210219114633-digital_audio_processing.org

72 lines
1.6 KiB
Org Mode
Raw Permalink Normal View History

2021-07-29 22:51:04 +00:00
:PROPERTIES:
:ID: 4d9e7aa6-1212-4487-84e7-5f9ac8205585
:END:
2021-02-20 02:30:40 +00:00
#+title: Digital Audio Processing
2021-02-20 05:17:58 +00:00
2021-07-29 22:51:04 +00:00
Analysis and manipulation of [[id:472c309f-d50b-4d3b-86cf-1af7c93db0b5][PCM Audio]].
2021-02-20 05:17:58 +00:00
2021-02-20 03:33:05 +00:00
* 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])
2021-02-20 05:17:58 +00:00
plt.title("Sine Wave")
2021-02-20 03:33:05 +00:00
plt.savefig("dap-sinewave.png")
return "dap-sinewave.png"
#+end_src
2021-02-20 03:33:37 +00:00
#+RESULTS:
[[file:dap-sinewave.png]]
2021-02-20 05:17:58 +00:00
* 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]]