Repository: xiongyihui/tdoa
Branch: master
Commit: e71681429fd2
Files: 13
Total size: 30.0 KB
Directory structure:
gitextract_nckaehmj/
├── .gitignore
├── LICENSE
├── README.md
├── bar_widget.py
├── echo_delay.py
├── gcc_phat.py
├── octave/
│ ├── gcc_phat.m
│ ├── test.m
│ └── view_cc.m
├── realtime_tdoa.py
├── vad.py
├── view.py
└── view_with_band_pass_filter.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: README.md
================================================
# TDOA
TDOA (Time Difference of Arrival) is estimated using GCC-PHAT.
A realtime DOA (Direction Of Arrival) is also elstimated using 2 microphones.
## Requirements
+ NumPy
+ PyAudio
+ WebRTCVAD
## Get started
```
python realtime_tdoa.py
```
================================================
FILE: bar_widget.py
================================================
from PySide import QtGui
class BarWidget(QtGui.QWidget):
def __init__(self):
super(BarWidget, self).__init__()
self.bars_number = 16
self.bars = [1] * self.bars_number
self.padding = 2
self.resolution = 255
self.setMinimumSize(240, 320)
def setBars(self, bars):
self.bars_number = len(bars)
for index, value in enumerate(bars):
if value > self.resolution:
bars[index] = self.resolution
self.bars = bars
self.update()
def paintEvent(self, e):
painter = QtGui.QPainter()
painter.begin(self)
self.drawBars(painter)
painter.end()
def drawBars(self, painter):
size = self.size()
width = size.width()
height = size.height()
bar_width = float(width - self.padding) / self.bars_number
color = QtGui.QColor(0, 0, 0)
painter.setPen(color)
painter.setBrush(color)
painter.drawRect(0, 0, width, height)
for bar, value in enumerate(self.bars):
bar_height = (height - self.padding) * value / self.resolution
if not bar_height:
bar_height = 1
painter.setBrush(self.barColor(bar))
painter.drawRect(
bar * bar_width + self.padding,
height - bar_height,
bar_width - self.padding,
bar_height - self.padding)
def barColor(self, bar):
position = int((bar + 0.5) * 255 / self.bars_number)
return self.palette(position)
def blue2red(self, position):
position &= 0xFF
if position < 128:
return QtGui.QColor(0, position * 2, 255 - position * 2)
else:
position -= 128
return QtGui.QColor(position * 2, 255 - position * 2, 0)
palette = blue2red
def main():
import sys
app = QtGui.QApplication(sys.argv)
BarWidget().show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
================================================
FILE: echo_delay.py
================================================
import sys
import wave
import numpy as np
from gcc_phat import gcc_phat
if len(sys.argv) != 3:
print('Usage: {} near.wav far.wav'.format(sys.argv[0]))
sys.exit(1)
near = wave.open(sys.argv[1], 'rb')
far = wave.open(sys.argv[2], 'rb')
rate = near.getframerate()
N = rate
window = np.hanning(N)
while True:
sig = near.readframes(N)
if len(sig) != 2 * N:
break
ref = far.readframes(N)
sig_buf = np.fromstring(sig, dtype='int16')
ref_buf = np.fromstring(ref, dtype='int16')
tau, _ = gcc_phat(sig_buf * window, ref_buf * window, fs=rate, max_tau=1)
# tau, _ = gcc_phat(sig_buf, ref_buf, fs=rate, max_tau=1)
print(tau * 1000)
================================================
FILE: gcc_phat.py
================================================
"""
Estimate time delay using GCC-PHAT
Copyright (c) 2017 Yihui Xiong
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=16):
'''
This function computes the offset between the signal sig and the reference signal refsig
using the Generalized Cross Correlation - Phase Transform (GCC-PHAT)method.
'''
# make sure the length for the FFT is larger or equal than len(sig) + len(refsig)
n = sig.shape[0] + refsig.shape[0]
# Generalized Cross Correlation Phase Transform
SIG = np.fft.rfft(sig, n=n)
REFSIG = np.fft.rfft(refsig, n=n)
R = SIG * np.conj(REFSIG)
cc = np.fft.irfft(R / np.abs(R), n=(interp * n))
max_shift = int(interp * n / 2)
if max_tau:
max_shift = np.minimum(int(interp * fs * max_tau), max_shift)
cc = np.concatenate((cc[-max_shift:], cc[:max_shift+1]))
# find max cross correlation index
shift = np.argmax(cc) - max_shift
# Sometimes, there is a 180-degree phase difference between the two microphones.
# shift = np.argmax(np.abs(cc)) - max_shift
tau = shift / float(interp * fs)
return tau, cc
def main():
refsig = np.linspace(1, 10, 10)
for i in range(0, 10):
sig = np.concatenate((np.linspace(0, 0, i), refsig, np.linspace(0, 0, 10 - i)))
offset, _ = gcc_phat(sig, refsig)
print(offset)
if __name__ == "__main__":
main()
================================================
FILE: octave/gcc_phat.m
================================================
function [tau, cc] = gcc_phat(sig, refsig, fs, max_tau, interp)
n = length(sig) + length(refsig);
max_shift = floor(n / 2);
if nargin < 3
fs = 1;
end
if nargin >= 4
max_shift = min(floor(fs * max_tau), max_shift);
end
if nargin < 5
interp = 1;
end
max_shift = max_shift * interp;
X1 = fft(sig, n);
X2 = fft(refsig, n);
R = X1 .* conj(X2);
cc = ifft(R ./ (abs(R)), n * interp);
N = length(cc);
cc = [cc((N - max_shift + 1):N)(:); cc(1:(max_shift + 1))(:)];
cc = abs(cc);
[max_cc, shift] = max(cc);
shift -= max_shift + 1;
tau = shift / (interp * fs);
end
================================================
FILE: octave/test.m
================================================
x1 = 0:1:10;
for i = 1:10
x2 = [zeros(1, i), x1];
delay = gcc_phat(x2, x1)
end
================================================
FILE: octave/view_cc.m
================================================
[far, fs] = audioread('../audio/alexa-01.wav');
[near, fs] = audioread('../audio/alexa-02.wav');
% 0.14 m is the distance of the two microphones
% 340 m/s as the sound speech
max_tau = 0.14 / 340;
audio_length = length(far);
block_length = floor(fs / 2);
n = floor(audio_length / block_length);
samples = floor(max_tau * fs) * 2 + 1;
z = zeros(samples, n);
window = hanning(block_length);
for k = 1:n
i = (k - 1) * block_length + 1;
sig = near(i:(i + block_length - 1)) .* window;
refsig = far(i:(i + block_length - 1)) .* window;
[tau, cc] = gcc_phat(sig, refsig, fs, max_tau);
z(:,k) = abs(cc);
end
surf(z);
colormap(hot)
================================================
FILE: realtime_tdoa.py
================================================
"""
Estimate realtime DoA (Direction of Arrival) using two mic
Copyright (c) 2017 Yihui Xiong
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import pyaudio
import webrtcvad
import numpy as np
import collections
import Queue
import threading
import signal
import sys
import math
import audioop
from gcc_phat import gcc_phat
from vad import vad
class Microphone:
def __init__(self, rate=16000, channels=2):
self.pyaudio_instance = pyaudio.PyAudio()
self.queue = Queue.Queue()
self.quit_event = threading.Event()
self.channels = channels
self.sample_rate = rate
def _callback(self, in_data, frame_count, time_info, status):
self.queue.put(in_data)
return None, pyaudio.paContinue
def read_chunks(self, size):
device_index = None
# for i in range(self.pyaudio_instance.get_device_count()):
# dev = self.pyaudio_instance.get_device_info_by_index(i)
# name = dev['name'].encode('utf-8')
# print(i, name, dev['maxInputChannels'], dev['maxOutputChannels'])
# if dev['maxInputChannels'] >= self.channels:
# print('Use {}'.format(name))
# device_index = i
# break
# if not device_index:
# print('can not find input device with {} channel(s)'.format(self.channels))
# return
stream = self.pyaudio_instance.open(
input=True,
format=pyaudio.paInt16,
channels=self.channels,
rate=self.sample_rate,
frames_per_buffer=size,
stream_callback=self._callback,
input_device_index = device_index,
)
while not self.quit_event.is_set():
frames = self.queue.get()
if not frames:
break
yield frames
stream.close()
def close(self):
self.quit_event.set()
self.queue.put('')
def main():
sample_rate = 48000
channels = 2
N = 4096 * 4
mic = Microphone(sample_rate, channels)
window = np.hanning(N)
sound_speed = 343.2
distance = 0.14
max_tau = distance / sound_speed
def signal_handler(sig, num):
print('Quit')
mic.close()
signal.signal(signal.SIGINT, signal_handler)
for data in mic.read_chunks(N):
buf = np.fromstring(data, dtype='int16')
mono = buf[0::channels].tostring()
if sample_rate != 16000:
mono, _ = audioop.ratecv(mono, 2, 1, sample_rate, 16000, None)
if vad.is_speech(mono):
tau, _ = gcc_phat(buf[0::channels]*window, buf[1::channels]*window, fs=sample_rate, max_tau=max_tau)
theta = math.asin(tau / max_tau) * 180 / math.pi
print('\ntheta: {}'.format(int(theta)))
if __name__ == '__main__':
main()
================================================
FILE: vad.py
================================================
"""
Voice Activity Detector based on WebRTC VAD (https://github.com/wiseman/py-webrtcvad)
Copyright (c) 2016 Seeed Technology Limited.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import collections
import sys
import webrtcvad
class WebRTCVAD:
def __init__(self, sample_rate=16000, level=3):
"""
Args:
sample_rate: audio sample rate
level: between 0 and 3. 0 is the least aggressive about filtering out non-speech, 3 is the most aggressive.
"""
self.sample_rate = sample_rate
self.frame_ms = 30
self.frame_bytes = int(2 * self.frame_ms * self.sample_rate / 1000) # S16_LE, 2 bytes width
self.vad = webrtcvad.Vad(level)
self.active = False
self.data = b''
self.history = collections.deque(maxlen=128)
def is_speech(self, data):
self.data += data
while len(self.data) >= self.frame_bytes:
frame = self.data[:self.frame_bytes]
self.data = self.data[self.frame_bytes:]
if self.vad.is_speech(frame, self.sample_rate):
sys.stdout.write('1')
self.history.append(1)
else:
sys.stdout.write('0')
self.history.append(0)
num_voiced = 0
for i in range(-8, 0):
try:
num_voiced += self.history[i]
except IndexError:
continue
if not self.active:
if num_voiced >= 4:
sys.stdout.write('+')
self.active = True
break
elif len(self.history) == self.history.maxlen and sum(self.history) == 0:
for _ in range(self.history.maxlen / 2):
self.history.popleft()
else:
if num_voiced < 1:
sys.stdout.write('-')
self.active = False
elif sum(self.history) > self.history.maxlen * 0.9:
for _ in range(int(self.history.maxlen / 2)):
self.history.popleft()
sys.stdout.flush()
return self.active
def reset(self):
self.data = b''
self.active = False
self.history.clear()
vad = WebRTCVAD()
================================================
FILE: view.py
================================================
import sys
import threading
import Queue
import audioop
import math
import pyaudio
import numpy as np
from gcc_phat import gcc_phat
RATE = 48000
FRAMES = int(RATE / 4)
window = np.hanning(FRAMES)
sound_speed = 343.2
distance = 0.14
max_tau = distance / sound_speed
direction_n = int(max_tau * RATE)
class DOA:
def __init__(self):
self.pyaudio_instance = pyaudio.PyAudio()
self.queue = Queue.Queue()
self.event = threading.Event()
def start(self, quit_event=None, show=None):
stream = self.pyaudio_instance.open(
rate=RATE,
frames_per_buffer=FRAMES,
format=pyaudio.paInt16,
channels=2,
input=True,
# output_device_index=1,
stream_callback=self._callback)
self.event.clear()
if not quit_event:
quit_event = threading.Event()
phat = [0] * (2 * direction_n + 1)
while not (quit_event.is_set() or self.event.is_set()):
try:
data = self.queue.get()
buf = np.fromstring(data, dtype='int16')
tau, cc = gcc_phat(buf[0::2] * window, buf[1::2] * window, fs=RATE, max_tau=max_tau, interp=1)
theta = math.asin(tau / max_tau) * 180 / math.pi
print('\ntheta: {}'.format(int(theta)))
for i, v in enumerate(cc):
phat[i] = int(v * 512)
if show:
show(phat)
# print [l for l in level]
except KeyboardInterrupt:
break
stream.close()
def _callback(self, in_data, frame_count, time_info, status):
self.queue.put(in_data)
return None, pyaudio.paContinue
def main():
from PySide import QtGui
from bar_widget import BarWidget
app = QtGui.QApplication(sys.argv)
widget = BarWidget()
widget.setWindowTitle('Direction Of Arrival')
widget.show()
doa = DOA()
quit_event = threading.Event()
thread = threading.Thread(target=doa.start, args=(quit_event, widget.setBars))
thread.start()
app.exec_()
quit_event.set()
thread.join()
if __name__ == '__main__':
main()
================================================
FILE: view_with_band_pass_filter.py
================================================
import sys
import threading
import Queue
import audioop
import math
import pyaudio
import numpy as np
from gcc_phat import gcc_phat
RATE = 48000
FRAMES = int(RATE / 4)
window = np.hanning(FRAMES)
sound_speed = 343.2
distance = 0.14
max_tau = distance / sound_speed
direction_n = int(max_tau * RATE)
def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=1):
'''
This function computes the offset between the signal sig and the reference signal refsig
using the Generalized Cross Correlation - Phase Transform (GCC-PHAT)method.
'''
# make sure the length for the FFT is larger or equal than len(sig) + len(refsig)
n = sig.shape[0] + refsig.shape[0]
low_cutoff_bin = int((250 * n) / RATE)
high_cutoff_bin = int((4000 * n) / RATE)
# Generalized Cross Correlation Phase Transform
SIG = np.fft.rfft(sig, n=n)
SIG[:low_cutoff_bin+1] = [0] * (low_cutoff_bin + 1)
SIG[-high_cutoff_bin:] = [0] * high_cutoff_bin
REFSIG = np.fft.rfft(refsig, n=n)
REFSIG[:low_cutoff_bin+1] = [0] * (low_cutoff_bin + 1)
REFSIG[-high_cutoff_bin:] = [0] * high_cutoff_bin
T = SIG[low_cutoff_bin+1:-high_cutoff_bin] * np.conj(REFSIG[low_cutoff_bin+1:-high_cutoff_bin])
T /= np.abs(T)
SIG[low_cutoff_bin+1:-high_cutoff_bin] = T
cc = np.fft.irfft(SIG, n=(interp * n))
max_shift = int(interp * n / 2)
if max_tau:
max_shift = np.minimum(int(interp * fs * max_tau), max_shift)
cc = np.concatenate((cc[-max_shift:], cc[:max_shift + 1]))
# find max cross correlation index
shift = np.argmax(np.abs(cc)) - max_shift
tau = shift / float(interp * fs)
return tau, cc
class DOA:
def __init__(self):
self.pyaudio_instance = pyaudio.PyAudio()
self.queue = Queue.Queue()
self.event = threading.Event()
def start(self, quit_event=None, show=None):
stream = self.pyaudio_instance.open(
rate=RATE,
frames_per_buffer=FRAMES,
format=pyaudio.paInt16,
channels=2,
input=True,
# output_device_index=1,
stream_callback=self._callback)
self.event.clear()
if not quit_event:
quit_event = threading.Event()
phat = [0] * (2 * direction_n + 1)
while not (quit_event.is_set() or self.event.is_set()):
try:
data = self.queue.get()
buf = np.fromstring(data, dtype='int16')
tau, cc = gcc_phat(buf[0::2] * window, buf[1::2] * window, fs=RATE, max_tau=max_tau, interp=1)
theta = math.asin(tau / max_tau) * 180 / math.pi
print('\ntheta: {}'.format(int(theta)))
for i, v in enumerate(cc):
phat[i] = int(v * 512)
if show:
show(phat)
# print [l for l in level]
except KeyboardInterrupt:
break
stream.close()
def _callback(self, in_data, frame_count, time_info, status):
self.queue.put(in_data)
return None, pyaudio.paContinue
def main():
from PySide import QtGui
from bar_widget import BarWidget
app = QtGui.QApplication(sys.argv)
widget = BarWidget()
widget.setWindowTitle('Direction Of Arrival')
widget.show()
doa = DOA()
quit_event = threading.Event()
thread = threading.Thread(target=doa.start, args=(quit_event, widget.setBars))
thread.start()
app.exec_()
quit_event.set()
thread.join()
if __name__ == '__main__':
main()
gitextract_nckaehmj/ ├── .gitignore ├── LICENSE ├── README.md ├── bar_widget.py ├── echo_delay.py ├── gcc_phat.py ├── octave/ │ ├── gcc_phat.m │ ├── test.m │ └── view_cc.m ├── realtime_tdoa.py ├── vad.py ├── view.py └── view_with_band_pass_filter.py
SYMBOL INDEX (31 symbols across 6 files)
FILE: bar_widget.py
class BarWidget (line 5) | class BarWidget(QtGui.QWidget):
method __init__ (line 6) | def __init__(self):
method setBars (line 16) | def setBars(self, bars):
method paintEvent (line 24) | def paintEvent(self, e):
method drawBars (line 31) | def drawBars(self, painter):
method barColor (line 53) | def barColor(self, bar):
method blue2red (line 57) | def blue2red(self, position):
function main (line 68) | def main():
FILE: gcc_phat.py
function gcc_phat (line 21) | def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=16):
function main (line 54) | def main():
FILE: realtime_tdoa.py
class Microphone (line 32) | class Microphone:
method __init__ (line 34) | def __init__(self, rate=16000, channels=2):
method _callback (line 41) | def _callback(self, in_data, frame_count, time_info, status):
method read_chunks (line 45) | def read_chunks(self, size):
method close (line 78) | def close(self):
function main (line 83) | def main():
FILE: vad.py
class WebRTCVAD (line 24) | class WebRTCVAD:
method __init__ (line 25) | def __init__(self, sample_rate=16000, level=3):
method is_speech (line 42) | def is_speech(self, data):
method reset (line 83) | def reset(self):
FILE: view.py
class DOA (line 25) | class DOA:
method __init__ (line 26) | def __init__(self):
method start (line 31) | def start(self, quit_event=None, show=None):
method _callback (line 66) | def _callback(self, in_data, frame_count, time_info, status):
function main (line 72) | def main():
FILE: view_with_band_pass_filter.py
function gcc_phat (line 25) | def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=1):
class DOA (line 66) | class DOA:
method __init__ (line 67) | def __init__(self):
method start (line 72) | def start(self, quit_event=None, show=None):
method _callback (line 107) | def _callback(self, in_data, frame_count, time_info, status):
function main (line 113) | def main():
Condensed preview — 13 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (32K chars).
[
{
"path": ".gitignore",
"chars": 1045,
"preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 246,
"preview": "# TDOA\n\nTDOA (Time Difference of Arrival) is estimated using GCC-PHAT.\nA realtime DOA (Direction Of Arrival) is also els"
},
{
"path": "bar_widget.py",
"chars": 2033,
"preview": "\nfrom PySide import QtGui\n\n\nclass BarWidget(QtGui.QWidget):\n def __init__(self):\n super(BarWidget, self).__ini"
},
{
"path": "echo_delay.py",
"chars": 678,
"preview": "\nimport sys\nimport wave\nimport numpy as np\nfrom gcc_phat import gcc_phat\n\n\nif len(sys.argv) != 3:\n print('Usage: {} n"
},
{
"path": "gcc_phat.py",
"chars": 1955,
"preview": "\"\"\"\n Estimate time delay using GCC-PHAT \n Copyright (c) 2017 Yihui Xiong\n\n Licensed under the Apache License, Version 2."
},
{
"path": "octave/gcc_phat.m",
"chars": 573,
"preview": "function [tau, cc] = gcc_phat(sig, refsig, fs, max_tau, interp)\n\nn = length(sig) + length(refsig);\nmax_shift = floor(n /"
},
{
"path": "octave/test.m",
"chars": 86,
"preview": "\n\nx1 = 0:1:10;\n\nfor i = 1:10\n x2 = [zeros(1, i), x1];\n\n delay = gcc_phat(x2, x1)\nend"
},
{
"path": "octave/view_cc.m",
"chars": 672,
"preview": "\r\n\r\n\r\n\r\n[far, fs] = audioread('../audio/alexa-01.wav');\r\n[near, fs] = audioread('../audio/alexa-02.wav');\r\n\r\n% 0.14 m is"
},
{
"path": "realtime_tdoa.py",
"chars": 3471,
"preview": "\"\"\"\r\n Estimate realtime DoA (Direction of Arrival) using two mic\r\n Copyright (c) 2017 Yihui Xiong\r\n\r\n Licensed under the"
},
{
"path": "vad.py",
"chars": 2824,
"preview": "\"\"\"\n Voice Activity Detector based on WebRTC VAD (https://github.com/wiseman/py-webrtcvad)\n Copyright (c) 2016 Seeed Tec"
},
{
"path": "view.py",
"chars": 2217,
"preview": "\n\nimport sys\nimport threading\nimport Queue\nimport audioop\nimport math\nimport pyaudio\nimport numpy as np\nfrom gcc_phat im"
},
{
"path": "view_with_band_pass_filter.py",
"chars": 3566,
"preview": "\n\nimport sys\nimport threading\nimport Queue\nimport audioop\nimport math\nimport pyaudio\nimport numpy as np\nfrom gcc_phat im"
}
]
About this extraction
This page contains the full source code of the xiongyihui/tdoa GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 13 files (30.0 KB), approximately 7.5k tokens, and a symbol index with 31 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.