Skip to content

Commit af9a973

Browse files
committed
develop Noise class and Hn class
1 parent 28d4061 commit af9a973

File tree

7 files changed

+306
-71
lines changed

7 files changed

+306
-71
lines changed

Hn.txt

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
-0.0001
2+
0.0000
3+
0.0004
4+
0.0013
5+
0.0028
6+
0.0047
7+
0.0068
8+
0.0085
9+
0.0090
10+
0.0078
11+
0.0050
12+
0.0008
13+
-0.0036
14+
-0.0067
15+
-0.0075
16+
-0.0053
17+
-0.0007
18+
0.0048
19+
0.0091
20+
0.0101
21+
0.0069
22+
0.0002
23+
-0.0077
24+
-0.0137
25+
-0.0147
26+
-0.0094
27+
0.0010
28+
0.0131
29+
0.0219
30+
0.0228
31+
0.0135
32+
-0.0043
33+
-0.0250
34+
-0.0402
35+
-0.0414
36+
-0.0229
37+
0.0158
38+
0.0692
39+
0.1265
40+
0.1748
41+
0.2024
42+
0.2024
43+
0.1748
44+
0.1265
45+
0.0692
46+
0.0158
47+
-0.0229
48+
-0.0414
49+
-0.0402
50+
-0.0250
51+
-0.0043
52+
0.0135
53+
0.0228
54+
0.0219
55+
0.0131
56+
0.0010
57+
-0.0094
58+
-0.0147
59+
-0.0137
60+
-0.0077
61+
0.0002
62+
0.0069
63+
0.0101
64+
0.0091
65+
0.0048
66+
-0.0007
67+
-0.0053
68+
-0.0075
69+
-0.0067
70+
-0.0036
71+
0.0008
72+
0.0050
73+
0.0078
74+
0.0090
75+
0.0085
76+
0.0068
77+
0.0047
78+
0.0028
79+
0.0013
80+
0.0004
81+
0.0000
82+
-0.0001

Sound.py

Lines changed: 0 additions & 71 deletions
This file was deleted.

main.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
from sound import Noise,Hn
2+
#
3+
# s1 = Noise(path='./M1.wav', name='M1')
4+
# s1.draw_fft()
5+
#
6+
# s2 = Noise(path='./M2.wav', name='M2')
7+
# s2.draw_fft()
8+
# #
9+
s3 = Noise(path='./M3.wav', name='M3')
10+
shifted = s3.shift_right(0.001)
11+
# s3.draw()
12+
# s3.hear_noise()
13+
# print(s3.when_max())
14+
# Reading Hn
15+
hn = Hn(path='./Hn.txt')
16+
# hn.draw()
17+
18+
# conv = s3.convolve(hn)
19+
# print(conv.get_duration())
20+
# slc = conv.get_slice(float(0.2))
21+
# print(slc.get_duration())
22+
# slc_conv = slc.convolve(conv)
23+
# slc_conv.draw()
24+
25+

new_sound_draw.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import matplotlib.pyplot as plt
2+
3+
from scipy.io import wavfile
4+
5+
samplerate,date = wavfile.read('1980s-Casio-Piano-C5.wav','r')
6+
print(samplerate)

sampleSound.py

Whitespace-only changes.

sound.py

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
import matplotlib.pyplot as plt
2+
import numpy as np
3+
from IPython.lib.display import Audio
4+
from scipy.io import wavfile
5+
from scipy.fftpack import fft, fftfreq
6+
import logging
7+
from tempfile import mkdtemp
8+
import os.path as path
9+
import sys
10+
11+
logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w',
12+
format='%(levelname)s - %(name)s: %(message)s')
13+
14+
15+
def printCmd(str):
16+
h = (32 * '-') + '\n'
17+
print(h + str + '\n' + h)
18+
19+
20+
class Hn:
21+
def __init__(self, **kwargs):
22+
self.data = []
23+
self.name = 'H[n]'
24+
self.path = None
25+
self.points = [[], []]
26+
if kwargs['path'] != '':
27+
self.path = kwargs['path']
28+
file = open(self.path, 'r')
29+
for line in file:
30+
self.data += [float(line)]
31+
elif kwargs['data']:
32+
self.data = kwargs['data']
33+
elif kwargs['path'] != '' and kwargs['data']:
34+
logging.debug('please insert a path or array of data')
35+
raise AttributeError('please insert a path or array of data')
36+
else:
37+
logging.debug('please insert a path or array of data')
38+
raise AttributeError('please insert a path or array of data')
39+
logging.info('Hn = {}'.format(str(self.data)))
40+
41+
for i in range(len(self.data)):
42+
self.points[0] += [i]
43+
self.points[1] += [self.data[i]]
44+
45+
def draw(self):
46+
plt.title(self.name)
47+
plt.plot(self.points[0], self.points[1])
48+
plt.xlabel('Rate')
49+
plt.ylabel('Amplitude')
50+
plt.show()
51+
52+
def draw_phase(self):
53+
plt.title(self.name + 'Phase spectrum')
54+
plt.phase_spectrum(self.points[1])
55+
plt.show()
56+
57+
def __str__(self):
58+
return self.data
59+
60+
61+
class Noise:
62+
def __init__(self, **kwargs):
63+
self.data = []
64+
self.sample_rate = 0
65+
self.fft = []
66+
self.frame = 0
67+
self.path = None
68+
69+
if kwargs['path']:
70+
self.path = kwargs['path']
71+
self.parse_wav()
72+
elif kwargs['data'] is not None:
73+
self.data = kwargs['data']
74+
self.sample_rate = 32000
75+
logging.info('noise data = {}'.format(self.data))
76+
elif kwargs['path'] != '' and kwargs['data']:
77+
logging.debug('please insert a path or array of data')
78+
raise AttributeError('please insert a path or array of data')
79+
else:
80+
logging.debug('please insert a path or array of data')
81+
raise AttributeError('please insert a path or array of data')
82+
83+
try:
84+
self.name = kwargs['name']
85+
except:
86+
self.name = 'Unknown' if self.path is None else self.path
87+
88+
logging.info('{} noise created.'.format(self.name))
89+
90+
def parse_wav(self):
91+
sample_rate, data = wavfile.read(self.path, 'r')
92+
self.data = data
93+
self.sample_rate = sample_rate
94+
logging.info('noise sample rate = {}'.format(self.sample_rate))
95+
logging.info('noise data = {}'.format(self.data))
96+
return self.data
97+
98+
def init_fft(self):
99+
self.fft = fft(self.data)
100+
101+
def get_fft(self):
102+
self.init_fft()
103+
return self.fft
104+
105+
def get_energy(self):
106+
return np.sum((np.abs(self.data) ** 2) / (self.sample_rate ** -1))
107+
108+
def get_duration(self):
109+
return len(self.data) / float(self.sample_rate)
110+
111+
def get_slice(self, slc):
112+
length = len(self.data)
113+
mul = (slc / self.get_duration()) * length
114+
index = int(mul)
115+
return Noise(name='{}s of {}'.format(slc, self.name), data=self.data[0:index], path='')
116+
117+
def get_max(self):
118+
return np.amax(self.data)
119+
120+
def when_max(self):
121+
length = len(self.data)
122+
index = np.where(self.data == self.get_max())
123+
when = ((index[0] * self.get_duration()) / length)[0]
124+
logging.info('{} at {}s is max'.format(self.name, when))
125+
return when
126+
127+
def shift_right(self, slc):
128+
amount = int(slc * self.sample_rate)
129+
filename = path.join(mkdtemp(), 'newfile.dat')
130+
fpath = np.memmap(filename, dtype='int16', mode='w+', shape=amount + len(self.data))
131+
fpath[amount::] = self.data
132+
logging.info('{} {} shifted right'.format(self.name, amount))
133+
return Noise(name='{} time shifted right {}'.format(amount, self.name),
134+
data=fpath, path='')
135+
136+
# Todo: check this function
137+
def shift_left(self, slc):
138+
amount = int(slc * self.sample_rate)
139+
filename = path.join(mkdtemp(), 'newfile.dat')
140+
fpath = np.memmap(filename, dtype='int16', mode='w+', shape=amount + len(self.data))
141+
fpath[::len(self.data)] = self.data
142+
logging.info('{} {} shifted left'.format(self.name, amount))
143+
return Noise(name='{} time shifted left {}'.format(amount, self.name),
144+
data=fpath, path='')
145+
146+
def reverse(self):
147+
self.data = [ele for ele in reversed(self.data)]
148+
149+
def draw(self):
150+
plt.figure(self.name, figsize=(12, 5))
151+
plt.title(self.name + ' Noise')
152+
time = np.arange(0, self.get_duration(), 1 / self.sample_rate) # time vector
153+
plt.plot(time, self.data)
154+
plt.xlabel('Time (s)')
155+
plt.ylabel('Amplitude')
156+
plt.grid(True)
157+
plt.show()
158+
159+
def draw_fft(self):
160+
self.init_fft()
161+
plt.figure(self.name + ' FFT')
162+
plt.plot(self.fft)
163+
plt.xlim([10, self.sample_rate / 2])
164+
plt.xscale('log')
165+
plt.grid(True)
166+
plt.xlabel('Frequency (Hz)')
167+
plt.show()
168+
169+
def draw_all(self):
170+
plt.figure(self.name)
171+
plt.plot(self.data)
172+
plt.grid(True)
173+
plt.figure(self.name + ' FFT')
174+
plt.plot(self.fft)
175+
plt.xlim([10, self.sample_rate / 2])
176+
plt.xscale('log')
177+
plt.grid(True)
178+
plt.xlabel('Frequency (Hz)')
179+
plt.show()
180+
181+
def draw_phase(self):
182+
plt.title(self.name + 'Phase spectrum')
183+
plt.phase_spectrum(self.data)
184+
plt.show()
185+
186+
def convolve(self, hn):
187+
return Noise(name='{} * {}'.format(self.name, hn.name), data=np.convolve(self.data, hn.data), path='')
188+
189+
def hear_noise(self):
190+
return Audio(data=self.data, rate=self.sample_rate)
191+
192+
def __str__(self):
193+
return self.data

soundDraw.py

Whitespace-only changes.

0 commit comments

Comments
 (0)