|
| 1 | +import sys |
| 2 | +import wave |
| 3 | +import numpy as np |
| 4 | + |
| 5 | + |
| 6 | +if len(sys.argv) != 2: |
| 7 | + print('Usage: {} multi.wav'.format(sys.argv[0])) |
| 8 | + sys.exit(1) |
| 9 | + |
| 10 | + |
| 11 | +multi = wave.open(sys.argv[1], 'rb') |
| 12 | +rate = multi.getframerate() |
| 13 | +channels = multi.getnchannels() |
| 14 | + |
| 15 | +if channels <= 1: |
| 16 | + sys.exit(1) |
| 17 | + |
| 18 | +N = rate |
| 19 | + |
| 20 | +window = np.hanning(N) |
| 21 | + |
| 22 | +interp = 4*8 |
| 23 | +max_offset = int(rate * 0.1 / 340 * interp) |
| 24 | + |
| 25 | +def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=16): |
| 26 | + ''' |
| 27 | + This function computes the offset between the signal sig and the reference signal refsig |
| 28 | + using the Generalized Cross Correlation - Phase Transform (GCC-PHAT)method. |
| 29 | + ''' |
| 30 | + |
| 31 | + # make sure the length for the FFT is larger or equal than len(sig) + len(refsig) |
| 32 | + n = sig.shape[0] + refsig.shape[0] |
| 33 | + |
| 34 | + # Generalized Cross Correlation Phase Transform |
| 35 | + SIG = np.fft.rfft(sig, n=n) |
| 36 | + REFSIG = np.fft.rfft(refsig, n=n) |
| 37 | + R = SIG * np.conj(REFSIG) |
| 38 | + #R /= np.abs(R) |
| 39 | + |
| 40 | + cc = np.fft.irfft(R, n=(interp * n)) |
| 41 | + |
| 42 | + max_shift = int(interp * n / 2) |
| 43 | + if max_tau: |
| 44 | + max_shift = np.minimum(int(interp * fs * max_tau), max_shift) |
| 45 | + |
| 46 | + cc = np.concatenate((cc[-max_shift:], cc[:max_shift+1])) |
| 47 | + |
| 48 | + # find max cross correlation index |
| 49 | + shift = np.argmax(np.abs(cc)) - max_shift |
| 50 | + |
| 51 | + tau = shift / float(interp * fs) |
| 52 | + |
| 53 | + return tau, cc |
| 54 | + |
| 55 | + |
| 56 | +print(multi.getsampwidth()) |
| 57 | + |
| 58 | +while True: |
| 59 | + data = multi.readframes(N) |
| 60 | + |
| 61 | + if len(data) != multi.getsampwidth() * N * channels: |
| 62 | + print("done") |
| 63 | + break |
| 64 | + |
| 65 | + if multi.getsampwidth() == 2: |
| 66 | + data = np.fromstring(data, dtype='int16') |
| 67 | + else: |
| 68 | + data = np.fromstring(data, dtype='int32') |
| 69 | + ref_buf = data[0::channels] |
| 70 | + |
| 71 | + offsets = [] |
| 72 | + for ch in range(1, channels): |
| 73 | + sig_buf = data[ch::channels] |
| 74 | + tau, _ = gcc_phat(sig_buf * window, ref_buf * window, fs=1, max_tau=max_offset, interp=interp) |
| 75 | + # tau, _ = gcc_phat(sig_buf, ref_buf, fs=rate, max_tau=1) |
| 76 | + |
| 77 | + offsets.append(tau) |
| 78 | + |
| 79 | + print(offsets) |
| 80 | + |
| 81 | +print(multi.getframerate()) |
| 82 | + |
| 83 | +multi.close() |
0 commit comments