1 | #! /usr/bin/python |
---|
2 | |
---|
3 | import sys |
---|
4 | from aubio import pvoc, source |
---|
5 | from numpy import array, arange, zeros, shape, log10, vstack |
---|
6 | from pylab import imshow, show, cm, axis, ylabel, xlabel, xticks, yticks |
---|
7 | |
---|
8 | def get_spectrogram(filename): |
---|
9 | samplerate = 44100 |
---|
10 | win_s = 512 # fft window size |
---|
11 | hop_s = win_s / 2 # hop size |
---|
12 | fft_s = win_s / 2 + 1 # spectrum bins |
---|
13 | |
---|
14 | a = source(filename, samplerate, hop_s) # source file |
---|
15 | pv = pvoc(win_s, hop_s) # phase vocoder |
---|
16 | specgram = zeros([0, fft_s], dtype='float32') # numpy array to store spectrogram |
---|
17 | |
---|
18 | # analysis |
---|
19 | while True: |
---|
20 | samples, read = a() # read file |
---|
21 | specgram = vstack((specgram,pv(samples).norm)) # store new norm vector |
---|
22 | if read < a.hop_size: break |
---|
23 | |
---|
24 | # plotting |
---|
25 | imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=cm.gray_r) |
---|
26 | axis([0, len(specgram), 0, len(specgram[0])]) |
---|
27 | ylabel('Frequency (Hz)') |
---|
28 | xlabel('Time (s)') |
---|
29 | # show axes in Hz and seconds |
---|
30 | time_step = hop_s / float(samplerate) |
---|
31 | total_time = len(specgram) * time_step |
---|
32 | ticks = 10 |
---|
33 | xticks( arange(ticks) / float(ticks) * len(specgram), |
---|
34 | [x * total_time / float(ticks) for x in range(ticks) ] ) |
---|
35 | yticks( arange(ticks) / float(ticks) * len(specgram[0]), |
---|
36 | [x * samplerate / 2. / float(ticks) for x in range(ticks) ] ) |
---|
37 | |
---|
38 | if __name__ == '__main__': |
---|
39 | if len(sys.argv) < 2: |
---|
40 | print "Usage: %s <filename>" % sys.argv[0] |
---|
41 | else: |
---|
42 | for soundfile in sys.argv[1:]: |
---|
43 | get_spectrogram(soundfile) |
---|
44 | # display graph |
---|
45 | show() |
---|