comparison service/audioInputLevels/audioInputLevelsAlsa.py @ 82:d288bc1174d4

audio input levels to graphite Ignore-this: b1422609f3bf51778b8b2284ca914916
author drewp@bigasterisk.com
date Fri, 02 Aug 2013 07:55:45 -0700
parents
children
comparison
equal deleted inserted replaced
81:ef639d892e77 82:d288bc1174d4
1 from __future__ import division
2 import argparse, alsaaudio, time, numpy, galena, socket
3
4 def sendRecentAudio(accum, galenaOut, prefix):
5 samples = numpy.concatenate(accum)
6 samples = abs(samples / (1<<15))
7
8 galenaOut.send(prefix + '.avg', numpy.average(samples))
9 galenaOut.send(prefix + '.max', numpy.amax(samples))
10
11 def sendForever(card, prefix, periodSec, galenaOut):
12 inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NORMAL, card)
13 inp.setchannels(1)
14 inp.setrate(44100)
15 inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
16 inp.setperiodsize(64)
17
18 readSleepSec = .05
19 lastSendTime = 0
20 accum = []
21 while True:
22
23 # I was getting machine hangs on an eeePC and I tried anything
24 # to make it not crash. I think this helped.
25 time.sleep(readSleepSec)
26
27 now = time.time()
28 if now - lastSendTime > periodSec * 2:
29 print "late: %s sec since last send and we have %s samples" % (
30 now - lastSendTime, sum(len(x) for x in accum))
31
32 nframes, data = inp.read()
33 if nframes <= 0:
34 #print 'nframes', nframes, len(data)
35 continue # i get -32 a lot, don't know why
36 samples = numpy.fromstring(data, dtype=numpy.int16)
37 accum.append(samples)
38
39 # -readSleepSec is in here to make sure we send a little too
40 # often (harmless) instead of missing a period sometimes,
41 # which makes a gap in the graph
42 if now > lastSendTime + periodSec - readSleepSec:
43 sendRecentAudio(accum, galenaOut, prefix)
44 lastSendTime = time.time()
45
46 accum[:] = []
47
48 parser = argparse.ArgumentParser()
49 parser.add_argument(
50 '--card', required=True,
51 help='alsa card name (see list of unindented lines from `arecord -L`)')
52
53 args = parser.parse_args()
54 sendForever(
55 prefix='system.house.audio.%s' % socket.gethostname(),
56 periodSec=2,
57 card=args.card,
58 galenaOut=galena.Galena(host='bang'),
59 )