-
Notifications
You must be signed in to change notification settings - Fork 0
/
main-2.py
65 lines (57 loc) · 2.02 KB
/
main-2.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# This is a simple demonstration on how to stream
# audio from microphone and then extract the pitch
# and volume directly with help of PyAudio and Aubio
# Python libraries. The PyAudio is used to interface
# the computer microphone. While the Aubio is used as
# a pitch detection object. There is also NumPy
# as well to convert format between PyAudio into
# the Aubio.
import aubio
import numpy as num
import pyaudio
import sys
# Some constants for setting the PyAudio and the
# Aubio.
BUFFER_SIZE = 2048
CHANNELS = 1
FORMAT = pyaudio.paFloat32
METHOD = "default"
SAMPLE_RATE = 44100
HOP_SIZE = BUFFER_SIZE//2
PERIOD_SIZE_IN_FRAME = HOP_SIZE
def main(args):
# Initiating PyAudio object.
pA = pyaudio.PyAudio()
# Open the microphone stream.
mic = pA.open(format=FORMAT, channels=CHANNELS,
rate=SAMPLE_RATE, input=True,
frames_per_buffer=PERIOD_SIZE_IN_FRAME)
# Initiating Aubio's pitch detection object.
pDetection = aubio.pitch(METHOD, BUFFER_SIZE,
HOP_SIZE, SAMPLE_RATE)
# Set unit.
pDetection.set_unit("Hz")
# Frequency under -40 dB will considered
# as a silence.
pDetection.set_silence(-40)
# Infinite loop!
while True:
# Always listening to the microphone.
data = mic.read(PERIOD_SIZE_IN_FRAME)
# Convert into number that Aubio understand.
samples = num.fromstring(data,
dtype=aubio.float_type)
# Finally get the pitch.
pitch = pDetection(samples)[0]
# Compute the energy (volume)
# of the current frame.
volume = num.sum(samples**2)/len(samples)
# Format the volume output so it only
# displays at most six numbers behind 0.
volume = "{:6f}".format(volume)
# Finally print the pitch and the volume.
print(str(pitch) + " " + str(volume))
f = open("/tmp/audio.txt", "w")
f.write(str(pitch))
#f.close()
if __name__ == "__main__": main(sys.argv)