First version
[ampy.git] / run.py
1 #!/usr/bin/python3
2 """
3 PyAudio example: Record a few seconds of audio and save to a WAVE
4 file.
5 """
6
7 import os
8 import pyaudio
9 import wave
10 import sys
11 import struct
12
13 DEVICE = 3  # which alsa decive to read
14 CHUNK = 1024  # how many bytes at a time?
15 FORMAT = pyaudio.paInt16  # Format
16 RATE = 44100
17 RECORD_SECONDS = 0.5
18
19 VOLUME_CONSTANT = 11.975454545454545
20
21 p = pyaudio.PyAudio()
22
23 stream = p.open(format=FORMAT,
24                 channels=1,  # Our ampmeter always returns 0 on the second channel
25                 rate=RATE,
26                 input=True,
27                 input_device_index=DEVICE,
28                 frames_per_buffer=CHUNK)
29
30 while(True):
31     total = 0
32     for i in range(0, int(RATE * RECORD_SECONDS / CHUNK)):
33         data = stream.read(CHUNK, exception_on_overflow=False)
34         values = struct.unpack('h'*CHUNK, data)
35         #print(values)
36         chunk_total = 0
37         for value in values:
38             if value > 0:
39                 chunk_total += value
40             else:
41                 chunk_total -= value
42         chunk_total /= len(values)
43         #print(chunk_total)
44         total += chunk_total
45     avg = total / int(RATE * RECORD_SECONDS / CHUNK)
46     watts = avg / VOLUME_CONSTANT
47     print("average {:.0f}W".format(watts))
48     os.system("rrdtool update power.rrd N:{:.0f}".format(watts))
49
50 stream.stop_stream()
51 stream.close()
52 p.terminate()
53