-
Notifications
You must be signed in to change notification settings - Fork 0
/
freqf2.py
96 lines (73 loc) · 2.12 KB
/
freqf2.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
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
from matplotlib.mlab import find
import pyaudio
import scikits.audiolab as audiolab
import numpy as np
import math
import wave
import os
def recordAudio():
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 1
WAVE_OUTPUT_FILENAME = "audioOriginal.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording:")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* Finished recording.")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
# Duplicate audio and save as Actual
frames, fs, encoder = audiolab.wavread('audioOriginal.wav')
audiolab.wavwrite(frames,'audioActual.wav',fs)
def Pitch(signal,rate):
signal = np.fromstring(signal, 'Int16');
crossing = [math.copysign(1.0, s) for s in signal]
index = find(np.diff(crossing));
if 2*np.prod(len(signal))==0:
return 0
else:
f0 = round(len(index) * rate /(2*np.prod(len(signal))))
return f0;
def playAudio():
import pyaudio
import wave
CHUNK = 1024
wf = wave.open('audioActual.wav', 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != '':
stream.write(data)
data = wf.readframes(CHUNK)
Frequency = Pitch(data, wf.getframerate())
print str(Frequency)+" Frequency"
stream.stop_stream()
stream.close()
p.terminate()
def main():
recordAudio()
playAudio()
os.remove('audioOriginal.wav')
os.remove('audioActual.wav')
if __name__ == "__main__":
main()