Repository navigation
Expand file tree
/
Copy pathpy5mon.py
More file actions
executable file
·216 lines (183 loc) · 4.62 KB
/
Copy pathpy5mon.py
File metadata and controls
executable file
·216 lines (183 loc) · 4.62 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 - Mathias Bøhn Grytemark
# Licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
# http://creativecommons.org/licenses/by-sa/3.0/
#
# Thanks to Justin Peel at stackoverflow.com for some code (the important part
# which gets me the frequencies used). http://stackoverflow.com/questions/2648151/python-frequency-detection/2649540#2649540
#
###############
from optparse import OptionParser
import pyaudio
import wave
import numpy
import sys
import os, stat
parser = OptionParser (usage="%prog [-d] [-i] [-p] FILE")
parser.add_option ("-d", "--debug", default=False, action='store_true', dest='debug', help='Enable debugging')
parser.add_option ("-p", "--play", default=False, action='store_true', dest='play', help='Play the file out loud')
parser.add_option ("-i", "--input", default=False, action='store_true', dest='input', help='Use line-in/mic as input instead of FILE. Do not specify FILE or -p with this.')
(options, args) = parser.parse_args ()
# lenght of file to inspect each run
frames = 1024
# play out loud?
if options.play:
play = True
else:
play = False
# debug?
if options.debug:
debug = True
else:
debug = False
# use mic/line-in?
if options.input:
ainput = True
else:
ainput = False
# filename comes as a positional argument:
if not ainput:
try:
if args[0]:
wavfile = args[0]
except:
parser.print_help ()
sys.exit(1)
if not os.path.isfile(wavfile) and not stat.S_ISFIFO(os.stat(wavfile).st_mode):
print "test"
parser.print_help ()
sys.exit(1)
if play:
pa = pyaudio.PyAudio ()
if not ainput:
wav = wave.open (wavfile, 'rb')
sw = wav.getsampwidth ()
rate = wav.getframerate ()
else:
pi = pyaudio.PyAudio ()
streaminput = pi.open (
format = pyaudio.paInt16,
rate = 22050,
channels = 1,
input = True,
frames_per_buffer = frames,
)
sw = pi.get_sample_size (pyaudio.paInt16)
rate = 22050
window = numpy.blackman (frames)
train = []
tonenone = 0
reffreq = {}
reffreq['1'] = 1124
reffreq['2'] = 1197
reffreq['3'] = 1275
reffreq['4'] = 1358
reffreq['5'] = 1446
reffreq['6'] = 1540
reffreq['7'] = 1640
reffreq['8'] = 1747
reffreq['9'] = 1860
reffreq['0'] = 1981
reffreq['a'] = 2400
reffreq['b'] = 930
reffreq['c'] = 2247
reffreq['d'] = 991
reffreq['e'] = 2110
reffreq['f'] = 1055
# need to remove decimals
def numdec (x):
return int('{0:g}'.format(x))
# look for right frequencies...
def checkfreq (freq, reffreq):
for rtone, rfreq in reffreq.items():
if rfreq-14 <= freq and rfreq+14 >= freq:
return rtone
# clean the train
def cleantrain (train):
lasttone = None
newtrain = []
for tone in train:
if not tone == lasttone:
newtrain.append (tone)
lasttone = tone
if len (newtrain) == 5:
printtrain (newtrain)
elif len (newtrain) == 10:
atrain = newtrain[:5]
btrain = newtrain[5:]
printtrain (atrain)
printtrain (btrain)
elif len (newtrain) == 15:
atrain = newtrain[:5]
btrain = newtrain[:5]
ctrain = newtrain[5:]
printtrain (atrain)
printtrain (btrain)
printtrain (ctrain)
elif len (newtrain) == 6:
printtrain (newtrain)
def printtrain (newtrain):
lasttone = None
for tone in newtrain:
if tone == 'e' and lasttone:
tone = lasttone
sys.stdout.write(str(tone))
lasttone = tone
sys.stdout.write("\n")
# this is to actually play the file
if play:
stream = pa.open (
format = pa.get_format_from_width (sw),
channels = wav.getnchannels (),
rate = rate,
output = True,
output_device_index=None,
)
if ainput:
data = streaminput.read (frames)
else:
data = wav.readframes (frames)
while len (data) == frames*sw:
if play:
stream.write (data)
indata = numpy.array (wave.struct.unpack ("%dh"%(len(data)/sw),data))*window
fftData = abs (numpy.fft.rfft(indata))**2
which = fftData[1:].argmax () + 1
if which != len (fftData)-1:
y0,y1,y2 = numpy.log (fftData[which-1:which+2])
x1 = (y2 - y0) * .5 / (2 * y1 - y2 - y0)
freq = (which + x1) * rate / frames
else:
freq = which * rate / frames
freq = numdec(round (freq))
tone = checkfreq (freq, reffreq)
if tone:
if debug:
print "Freq: %i (tone %s)" % (freq, tone)
train.append (tone)
tone = None
elif train and tone == None and tonenone == 3:
cleantrain (train)
train = []
tonenone = 0
elif train and tone == None and tonenone == 0:
tonenone = 1
elif train and tone == None and tonenone == 1:
tonenone = 2
elif train and tone == None and tonenone == 2:
tonenone = 3
elif debug:
print "Freq: %i" % (freq)
if ainput:
data = streaminput.read (frames)
else:
data = wav.readframes (frames)
if data and play:
stream.write (data)
if play:
stream.close ()
pa.terminate ()
if train:
cleantrain (train)