-
Notifications
You must be signed in to change notification settings - Fork 0
/
audio_processing.py
42 lines (36 loc) · 1.42 KB
/
audio_processing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a period of audio data and returns it.
##
## To test it out, run it and shout at your microphone:
# borrowed from https://www.raspberrypi.org/forums/viewtopic.php?t=212857
from struct import unpack
from typing import Optional
import numpy as np
import alsaaudio
from constants import NUM_CHANNELS, PERIOD_SIZE, SAMPLE_RATE
def read_input_audio(testing: bool = False) -> Optional[alsaaudio.PCM]:
# Open the device in blocking capture mode.
# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is sufficient to know that reads from the device
# will return this many frames
try:
I, data = alsaaudio.PCM(
alsaaudio.PCM_CAPTURE,
alsaaudio.PCM_NORMAL,
cardindex=1, # the USB audio device
channels=NUM_CHANNELS,
rate=SAMPLE_RATE,
format=alsaaudio.PCM_FORMAT_S16_LE,
periodsize=PERIOD_SIZE,
).read()
except alsaaudio.ALSAAudioError as e:
print(f"Error reading in audio {e}")
return None
unpacked_data = np.array(
unpack(str(2 * PERIOD_SIZE) + "B", data)
) # unpack from bytes
return unpacked_data