[7175ed4] | 1 | #! /usr/bin/env python |
---|
[e4c2169] | 2 | |
---|
[f6892d4] | 3 | import numpy as np |
---|
| 4 | import aubio |
---|
[e4c2169] | 5 | |
---|
| 6 | def build_sinusoid(length, freqs, samplerate): |
---|
[f6892d4] | 7 | return np.sin( 2. * np.pi * np.arange(length) * freqs / samplerate).astype(aubio.float_type) |
---|
[e4c2169] | 8 | |
---|
| 9 | def run_pitch(p, input_vec): |
---|
[f6892d4] | 10 | cands = [] |
---|
| 11 | for vec_slice in input_vec.reshape((-1, p.hop_size)): |
---|
| 12 | a = p(vec_slice)[0] |
---|
| 13 | cands.append(a) |
---|
| 14 | return cands |
---|
[e4c2169] | 15 | |
---|
| 16 | methods = ['default', 'schmitt', 'fcomb', 'mcomb', 'yin', 'yinfft'] |
---|
| 17 | |
---|
| 18 | cands = {} |
---|
| 19 | buf_size = 2048 |
---|
| 20 | hop_size = 512 |
---|
| 21 | samplerate = 44100 |
---|
| 22 | sin_length = (samplerate * 10) % 512 * 512 |
---|
[f6892d4] | 23 | freqs = np.zeros(sin_length) |
---|
[e4c2169] | 24 | |
---|
[4120fbc] | 25 | partition = sin_length // 8 |
---|
[e4c2169] | 26 | pointer = 0 |
---|
| 27 | |
---|
| 28 | pointer += partition |
---|
| 29 | freqs[pointer: pointer + partition] = 440 |
---|
| 30 | |
---|
| 31 | pointer += partition |
---|
| 32 | pointer += partition |
---|
| 33 | freqs[ pointer : pointer + partition ] = 740 |
---|
| 34 | |
---|
| 35 | pointer += partition |
---|
| 36 | freqs[ pointer : pointer + partition ] = 1480 |
---|
| 37 | |
---|
| 38 | pointer += partition |
---|
| 39 | pointer += partition |
---|
[1929be4] | 40 | freqs[ pointer : pointer + partition ] = 400 + 5 * np.random.random(sin_length//8) |
---|
[e4c2169] | 41 | |
---|
| 42 | a = build_sinusoid(sin_length, freqs, samplerate) |
---|
| 43 | |
---|
| 44 | for method in methods: |
---|
[f6892d4] | 45 | p = aubio.pitch(method, buf_size, hop_size, samplerate) |
---|
| 46 | cands[method] = run_pitch(p, a) |
---|
[4120fbc] | 47 | print(method) |
---|
| 48 | print(cands[method]) |
---|
[e4c2169] | 49 | |
---|
[4120fbc] | 50 | print("done computing") |
---|
[e4c2169] | 51 | |
---|
| 52 | if 1: |
---|
[f6892d4] | 53 | import matplotlib.pyplot as plt |
---|
[e4c2169] | 54 | |
---|
[f6892d4] | 55 | # times |
---|
| 56 | ramp = np.arange(0, sin_length / hop_size).astype('float') * hop_size / samplerate |
---|
[e4c2169] | 57 | |
---|
[f6892d4] | 58 | # plot each result |
---|
| 59 | for method in methods: |
---|
| 60 | plt.plot(ramp, cands[method], '.-', label=method) |
---|
[e4c2169] | 61 | |
---|
[f6892d4] | 62 | # plot ground truth |
---|
| 63 | ramp = np.arange(0, sin_length).astype('float') / samplerate |
---|
| 64 | plt.plot(ramp, freqs, ':', label = 'ground truth') |
---|
| 65 | |
---|
| 66 | plt.legend(loc='upper left') |
---|
| 67 | |
---|
| 68 | plt.xlabel('time (s)') |
---|
| 69 | plt.ylabel('frequency (Hz)') |
---|
| 70 | plt.ylim([0,2000]) |
---|
| 71 | plt.show() |
---|