├── .gitignore ├── .gitmodules ├── LICENSE ├── README.md ├── gcc_phat.py ├── google_assistant_for_raspberry_pi.py ├── google_home_lights.py ├── kws_doa.py ├── mic_array.py ├── odas.cfg ├── pixel_ring.py └── vad_doa.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "snowboy"] 2 | path = snowboy 3 | url = https://github.com/Kitt-AI/snowboy.git 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Mic Array 2 | ========= 3 | 4 | Utils for [ReSpeaker Microphone Array](https://www.seeedstudio.com/ReSpeaker-Mic-Array-Far-field-w--7-PDM-Microphones--p-2719.html). It includes DOA (Direction of Arrival), VAD (Voice Activity Detection), KWS (Keyword Spotting or Keyword Search) and etc. 5 | 6 | + `pixel_ring.py` - control the pixel ring 7 | + `mic_array.py` - read 8 channels raw audio from the Mic Array and estimate sound's DOA (Direction of Arrival) 8 | + `vad_doa.py` - do VAD (Voice Activity Detection) and then estimate DOA 9 | + `kws_doa.py` - search keyword and then estimate DOA 10 | 11 | ## Requirements 12 | + For ReSpeaker USB Mic Array - Far-field w/ 7 PDM Microphones 13 | 14 | Change the Mic Array's firmware to get 8 channels raw audio. See https://github.com/respeaker/mic_array_dfu 15 | 16 | + For 4 Mic Array Pi hat 17 | 18 | Install [seeed-voicecard](https://github.com/respeaker/seeed-voicecard) driver first. Change `CHANNELS = 8` to `CHANNELS = 4` in [vad_doa.py](https://github.com/respeaker/mic_array/blob/master/vad_doa.py#L10) and [kws_doa.py](https://github.com/respeaker/mic_array/blob/master/kws_doa.py#L11) 19 | 20 | ## Get started 21 | 1. Run `pixel_ring.py` to control the pixel ring of the Mic Array through USB HID 22 | 23 | ``` 24 | sudo pip install pyusb 25 | sudo python pixel_ring.py 26 | ``` 27 | If you don't want to access USB device with `sudo`, add a udev `.rules` file to `/etc/udev/rules.d`: 28 | ``` 29 | echo 'SUBSYSTEM=="usb", MODE="0666"' | sudo tee -a /etc/udev/rules.d/60-usb.rules 30 | sudo udevadm control -R # then re-plug the usb device 31 | ``` 32 | 33 | 2. Read 8 channels audio from the Mic Array and estimate sound's DOA 34 | ``` 35 | sudo apt-get install python-numpy # or pip install numpy 36 | python mic_array.py 37 | ``` 38 | 39 | 3. Do VAD and then estimate DOA 40 | ``` 41 | sudo pip install webrtcvad 42 | python vad_doa.py 43 | ``` 44 | 45 | 4. Do KWS and then estimate DOA 46 | 47 | Get snowboy work and run `python kws_doa.py` 48 | ``` 49 | git submodule init 50 | git submodule update 51 | cd snowboy/swig/Python 52 | sudo apt-get install python-dev libatlas-base-dev swig # requiremetns to compile snowboy 53 | make # if got an error of swig3.x.x, edit the Makefile and disable the swig version check. 54 | echo 'from snowboydetect import *' > __init__.py # create __init__.py for a python module 55 | cd ../../.. # chang to the root directory of the repository 56 | ln -s snowboy/swig/Python snowboydetect 57 | python kws_doa.py 58 | ``` 59 | 60 | ## For Raspberry Pi 61 | Google released [Google Assistant Library](https://github.com/googlesamples/assistant-sdk-python/tree/master/google-assistant-library) for Raspberry Pi to provide hotword detection ("Ok Google" or "Hey Google"), audio recording, assistant response playback and etc. We can add LED lights indicator based on the library to make a device very similar with Google Home. 62 | 63 | 1. Follow [the guide](https://github.com/googlesamples/assistant-sdk-python/tree/master/google-assistant-library) to install Google Assistant Library. 64 | 2. Run `python google_assistant_for_raspberry_pi.py` 65 | 66 | ## Use 4 Mic Array with ODAS to sound source localization and tracking 67 | [ODAS](https://github.com/introlab/odas) is a very cool project to perform sound source localization, tracking, separation and post-filtering. Let's have a try! 68 | 69 | 1. get ODAS and build it 70 | 71 | ``` 72 | sudo apt-get install libfftw3-dev libconfig-dev libasound2-dev 73 | git clone https://github.com/introlab/odas.git --branch=phoenix 74 | mkdir odas/build 75 | cd odas/build 76 | cmake .. 77 | make 78 | ``` 79 | 80 | 2. get ODAS Studio from https://github.com/introlab/odas_web/releases and open it. You can run ODAS Studio on a computer or the Raspberry Pi 81 | 82 | The `odascore` will be at `odas/bin/odascore`, the config file is at [odas.cfg](odas.cfg). Change `odas.cfg` based on your sound card number. 83 | 84 | 85 | ``` 86 | interface: { 87 | type = "soundcard"; 88 | card = 1; 89 | device = 0; 90 | } 91 | ``` 92 | 93 | If you run the ODAS Studio on a computer, you should also need to change IP address from `127.0.0.1` to the IP of the computer. 94 | 95 | 96 | ![](https://github.com/introlab/odas_web/raw/master/screenshots/live_data.png) 97 | 98 | 99 | -------------------------------------------------------------------------------- /gcc_phat.py: -------------------------------------------------------------------------------- 1 | """ 2 | Estimate time delay using GCC-PHAT 3 | Copyright (c) 2017 Yihui Xiong 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | """ 17 | 18 | import numpy as np 19 | 20 | 21 | def gcc_phat(sig, refsig, fs=1, max_tau=None, interp=16): 22 | ''' 23 | This function computes the offset between the signal sig and the reference signal refsig 24 | using the Generalized Cross Correlation - Phase Transform (GCC-PHAT)method. 25 | ''' 26 | 27 | # make sure the length for the FFT is larger or equal than len(sig) + len(refsig) 28 | n = sig.shape[0] + refsig.shape[0] 29 | 30 | # Generalized Cross Correlation Phase Transform 31 | SIG = np.fft.rfft(sig, n=n) 32 | REFSIG = np.fft.rfft(refsig, n=n) 33 | R = SIG * np.conj(REFSIG) 34 | 35 | cc = np.fft.irfft(R / np.abs(R), n=(interp * n)) 36 | 37 | max_shift = int(interp * n / 2) 38 | if max_tau: 39 | max_shift = np.minimum(int(interp * fs * max_tau), max_shift) 40 | 41 | cc = np.concatenate((cc[-max_shift:], cc[:max_shift+1])) 42 | 43 | # find max cross correlation index 44 | shift = np.argmax(np.abs(cc)) - max_shift 45 | 46 | tau = shift / float(interp * fs) 47 | 48 | return tau, cc 49 | 50 | 51 | def main(): 52 | 53 | refsig = np.linspace(1, 10, 10) 54 | 55 | for i in range(0, 10): 56 | sig = np.concatenate((np.linspace(0, 0, i), refsig, np.linspace(0, 0, 10 - i))) 57 | offset, _ = gcc_phat(sig, refsig) 58 | print(offset) 59 | 60 | 61 | if __name__ == "__main__": 62 | main() 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /google_assistant_for_raspberry_pi.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (C) 2017 Google Inc. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from __future__ import print_function 19 | 20 | import argparse 21 | import os.path 22 | import json 23 | 24 | import google.oauth2.credentials 25 | from google.assistant.library import Assistant 26 | from google.assistant.library.event import EventType 27 | from google.assistant.library.file_helpers import existing_file 28 | from google_home_lights import lights 29 | 30 | 31 | def process_event(event): 32 | """Pretty prints events. 33 | 34 | Prints all events that occur with two spaces between each new 35 | conversation and a single space between turns of a conversation. 36 | 37 | Args: 38 | event(event.Event): The current event to process. 39 | """ 40 | if event.type == EventType.ON_CONVERSATION_TURN_STARTED: 41 | print() 42 | lights.wakeup() 43 | 44 | print(event) 45 | 46 | if event.type == EventType.ON_END_OF_UTTERANCE: 47 | lights.think() 48 | 49 | if event.type == EventType.ON_RESPONDING_STARTED: 50 | lights.speak() 51 | 52 | if event.type == EventType.ON_CONVERSATION_TURN_FINISHED: 53 | if event.args and event.args['with_follow_on_turn']: 54 | lights.listen() 55 | else: 56 | lights.off() 57 | 58 | 59 | def main(): 60 | parser = argparse.ArgumentParser( 61 | formatter_class=argparse.RawTextHelpFormatter) 62 | parser.add_argument('--credentials', type=existing_file, 63 | metavar='OAUTH2_CREDENTIALS_FILE', 64 | default=os.path.join( 65 | os.path.expanduser('~/.config'), 66 | 'google-oauthlib-tool', 67 | 'credentials.json' 68 | ), 69 | help='Path to store and read OAuth2 credentials') 70 | args = parser.parse_args() 71 | with open(args.credentials, 'r') as f: 72 | credentials = google.oauth2.credentials.Credentials(token=None, 73 | **json.load(f)) 74 | 75 | with Assistant(credentials) as assistant: 76 | for event in assistant.start(): 77 | process_event(event) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /google_home_lights.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright (C) 2017 Seeed Technology Limited 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | 17 | 18 | from pixel_ring import pixel_ring 19 | import numpy 20 | import time 21 | import threading 22 | try: 23 | import queue as Queue 24 | except ImportError: 25 | import Queue as Queue 26 | 27 | 28 | class GoogleHomeLights: 29 | def __init__(self): 30 | self.basis = numpy.array([0] * 4 * 12) 31 | self.basis[0 * 4 + 0] = 2 32 | self.basis[3 * 4 + 2] = 2 33 | self.basis[6 * 4 + 1] = 1 34 | self.basis[6 * 4 + 2] = 1 35 | self.basis[9 * 4 + 1] = 2 36 | 37 | self.pixels = self.basis * 0 38 | self.write(self.pixels) 39 | 40 | pixel_ring.write(0, [6, 0, 0, 0]) 41 | 42 | self.next = threading.Event() 43 | self.queue = Queue.Queue() 44 | self.thread = threading.Thread(target=self._run) 45 | self.thread.daemon = True 46 | self.thread.start() 47 | 48 | def wakeup(self, direction=0): 49 | def f(): 50 | self._wakeup(direction) 51 | self.queue.put(f) 52 | 53 | def listen(self): 54 | self.next.set() 55 | self.queue.put(self._listen) 56 | 57 | def think(self): 58 | self.next.set() 59 | self.queue.put(self._think) 60 | 61 | def speak(self): 62 | self.next.set() 63 | self.queue.put(self._speak) 64 | 65 | def off(self): 66 | self.next.set() 67 | self.queue.put(self._off) 68 | 69 | 70 | def _run(self): 71 | while True: 72 | func = self.queue.get() 73 | func() 74 | 75 | def _wakeup(self, direction=0): 76 | position = int((direction + 15) / 30) % 12 77 | 78 | basis = numpy.roll(self.basis, position * 4) 79 | for i in range(1, 25): 80 | pixels = basis * i 81 | self.write(pixels) 82 | time.sleep(0.005) 83 | 84 | pixels = numpy.roll(pixels, 4) 85 | self.write(pixels) 86 | time.sleep(0.1) 87 | 88 | for i in range(2): 89 | new_pixels = numpy.roll(pixels, 4) 90 | self.write(new_pixels * 0.5 + pixels) 91 | pixels = new_pixels 92 | time.sleep(0.1) 93 | 94 | self.write(pixels) 95 | self.pixels = pixels 96 | 97 | def _listen(self): 98 | pixels = self.pixels 99 | for i in range(1, 25): 100 | self.write(pixels * i / 24) 101 | time.sleep(0.01) 102 | 103 | def _think(self): 104 | pixels = self.pixels 105 | 106 | self.next.clear() 107 | while not self.next.is_set(): 108 | pixels = numpy.roll(pixels, 4) 109 | self.write(pixels) 110 | time.sleep(0.2) 111 | 112 | t = 0.1 113 | for i in range(0, 5): 114 | pixels = numpy.roll(pixels, 4) 115 | self.write(pixels * (4 - i) / 4) 116 | time.sleep(t) 117 | t /= 2 118 | 119 | # time.sleep(0.5) 120 | 121 | self.pixels = pixels 122 | 123 | def _speak(self): 124 | pixels = self.pixels 125 | 126 | self.next.clear() 127 | while not self.next.is_set(): 128 | for i in range(5, 25): 129 | self.write(pixels * i / 24) 130 | time.sleep(0.01) 131 | 132 | time.sleep(0.3) 133 | 134 | for i in range(24, 4, -1): 135 | self.write(pixels * i / 24) 136 | time.sleep(0.01) 137 | 138 | time.sleep(0.3) 139 | 140 | self._off() 141 | 142 | def _off(self): 143 | self.write([0] * 4 * 12) 144 | 145 | def write(self, data): 146 | if type(data) is list: 147 | pixel_ring.write(3, data) 148 | else: 149 | pixel_ring.write(3, data.astype('uint8').tostring()) 150 | 151 | 152 | lights = GoogleHomeLights() 153 | 154 | 155 | if __name__ == '__main__': 156 | while True: 157 | 158 | try: 159 | lights.wakeup() 160 | time.sleep(3) 161 | lights.think() 162 | time.sleep(3) 163 | lights.speak() 164 | time.sleep(3) 165 | lights.off() 166 | time.sleep(3) 167 | except KeyboardInterrupt: 168 | break 169 | 170 | 171 | pixel_ring.off() -------------------------------------------------------------------------------- /kws_doa.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | import numpy as np 4 | import collections 5 | from mic_array import MicArray 6 | from pixel_ring import pixel_ring 7 | from snowboydetect import SnowboyDetect 8 | 9 | 10 | RATE = 16000 11 | CHANNELS = 4 12 | KWS_FRAMES = 10 # ms 13 | DOA_FRAMES = 800 # ms 14 | 15 | 16 | detector = SnowboyDetect('snowboy/resources/common.res', 'snowboy/resources/alexa/alexa_02092017.umdl') 17 | detector.SetAudioGain(1) 18 | detector.SetSensitivity('0.5') 19 | 20 | 21 | def main(): 22 | history = collections.deque(maxlen=int(DOA_FRAMES / KWS_FRAMES)) 23 | 24 | try: 25 | with MicArray(RATE, CHANNELS, RATE * KWS_FRAMES / 1000) as mic: 26 | for chunk in mic.read_chunks(): 27 | history.append(chunk) 28 | 29 | # Detect keyword from channel 0 30 | ans = detector.RunDetection(chunk[0::CHANNELS].tostring()) 31 | if ans > 0: 32 | frames = np.concatenate(history) 33 | direction = mic.get_direction(frames) 34 | pixel_ring.set_direction(direction) 35 | print('\n{}'.format(int(direction))) 36 | 37 | except KeyboardInterrupt: 38 | pass 39 | 40 | pixel_ring.off() 41 | 42 | 43 | if __name__ == '__main__': 44 | main() 45 | -------------------------------------------------------------------------------- /mic_array.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import pyaudio 4 | import Queue 5 | import threading 6 | import numpy as np 7 | from gcc_phat import gcc_phat 8 | import math 9 | 10 | 11 | SOUND_SPEED = 343.2 12 | 13 | MIC_DISTANCE_6P1 = 0.064 14 | MAX_TDOA_6P1 = MIC_DISTANCE_6P1 / float(SOUND_SPEED) 15 | 16 | MIC_DISTANCE_4 = 0.08127 17 | MAX_TDOA_4 = MIC_DISTANCE_4 / float(SOUND_SPEED) 18 | 19 | 20 | 21 | class MicArray(object): 22 | 23 | def __init__(self, rate=16000, channels=8, chunk_size=None): 24 | self.pyaudio_instance = pyaudio.PyAudio() 25 | self.queue = Queue.Queue() 26 | self.quit_event = threading.Event() 27 | self.channels = channels 28 | self.sample_rate = rate 29 | self.chunk_size = chunk_size if chunk_size else rate / 100 30 | 31 | device_index = None 32 | for i in range(self.pyaudio_instance.get_device_count()): 33 | dev = self.pyaudio_instance.get_device_info_by_index(i) 34 | name = dev['name'].encode('utf-8') 35 | print(i, name, dev['maxInputChannels'], dev['maxOutputChannels']) 36 | if dev['maxInputChannels'] == self.channels: 37 | print('Use {}'.format(name)) 38 | device_index = i 39 | break 40 | 41 | if device_index is None: 42 | raise Exception('can not find input device with {} channel(s)'.format(self.channels)) 43 | 44 | self.stream = self.pyaudio_instance.open( 45 | input=True, 46 | start=False, 47 | format=pyaudio.paInt16, 48 | channels=self.channels, 49 | rate=int(self.sample_rate), 50 | frames_per_buffer=int(self.chunk_size), 51 | stream_callback=self._callback, 52 | input_device_index=device_index, 53 | ) 54 | 55 | def _callback(self, in_data, frame_count, time_info, status): 56 | self.queue.put(in_data) 57 | return None, pyaudio.paContinue 58 | 59 | def start(self): 60 | self.queue.queue.clear() 61 | self.stream.start_stream() 62 | 63 | 64 | def read_chunks(self): 65 | self.quit_event.clear() 66 | while not self.quit_event.is_set(): 67 | frames = self.queue.get() 68 | if not frames: 69 | break 70 | 71 | frames = np.fromstring(frames, dtype='int16') 72 | yield frames 73 | 74 | def stop(self): 75 | self.quit_event.set() 76 | self.stream.stop_stream() 77 | self.queue.put('') 78 | 79 | def __enter__(self): 80 | self.start() 81 | return self 82 | 83 | def __exit__(self, type, value, traceback): 84 | if value: 85 | return False 86 | self.stop() 87 | 88 | def get_direction(self, buf): 89 | best_guess = None 90 | if self.channels == 8: 91 | MIC_GROUP_N = 3 92 | MIC_GROUP = [[1, 4], [2, 5], [3, 6]] 93 | 94 | tau = [0] * MIC_GROUP_N 95 | theta = [0] * MIC_GROUP_N 96 | 97 | # buf = np.fromstring(buf, dtype='int16') 98 | for i, v in enumerate(MIC_GROUP): 99 | tau[i], _ = gcc_phat(buf[v[0]::8], buf[v[1]::8], fs=self.sample_rate, max_tau=MAX_TDOA_6P1, interp=1) 100 | theta[i] = math.asin(tau[i] / MAX_TDOA_6P1) * 180 / math.pi 101 | 102 | min_index = np.argmin(np.abs(tau)) 103 | if (min_index != 0 and theta[min_index - 1] >= 0) or (min_index == 0 and theta[MIC_GROUP_N - 1] < 0): 104 | best_guess = (theta[min_index] + 360) % 360 105 | else: 106 | best_guess = (180 - theta[min_index]) 107 | 108 | best_guess = (best_guess + 120 + min_index * 60) % 360 109 | elif self.channels == 4: 110 | MIC_GROUP_N = 2 111 | MIC_GROUP = [[0, 2], [1, 3]] 112 | 113 | tau = [0] * MIC_GROUP_N 114 | theta = [0] * MIC_GROUP_N 115 | for i, v in enumerate(MIC_GROUP): 116 | tau[i], _ = gcc_phat(buf[v[0]::4], buf[v[1]::4], fs=self.sample_rate, max_tau=MAX_TDOA_4, interp=1) 117 | theta[i] = math.asin(tau[i] / MAX_TDOA_4) * 180 / math.pi 118 | 119 | if np.abs(theta[0]) < np.abs(theta[1]): 120 | if theta[1] > 0: 121 | best_guess = (theta[0] + 360) % 360 122 | else: 123 | best_guess = (180 - theta[0]) 124 | else: 125 | if theta[0] < 0: 126 | best_guess = (theta[1] + 360) % 360 127 | else: 128 | best_guess = (180 - theta[1]) 129 | 130 | best_guess = (best_guess + 90 + 180) % 360 131 | 132 | 133 | best_guess = (-best_guess + 120) % 360 134 | 135 | 136 | elif self.channels == 2: 137 | pass 138 | 139 | return best_guess 140 | 141 | 142 | def test_4mic(): 143 | import signal 144 | import time 145 | 146 | is_quit = threading.Event() 147 | 148 | def signal_handler(sig, num): 149 | is_quit.set() 150 | print('Quit') 151 | 152 | signal.signal(signal.SIGINT, signal_handler) 153 | 154 | with MicArray(16000, 4, 16000 / 4) as mic: 155 | for chunk in mic.read_chunks(): 156 | direction = mic.get_direction(chunk) 157 | print(int(direction)) 158 | 159 | if is_quit.is_set(): 160 | break 161 | 162 | 163 | def test_8mic(): 164 | import signal 165 | import time 166 | from pixel_ring import pixel_ring 167 | 168 | is_quit = threading.Event() 169 | 170 | def signal_handler(sig, num): 171 | is_quit.set() 172 | print('Quit') 173 | 174 | signal.signal(signal.SIGINT, signal_handler) 175 | 176 | with MicArray(16000, 8, 16000 / 4) as mic: 177 | for chunk in mic.read_chunks(): 178 | direction = mic.get_direction(chunk) 179 | pixel_ring.set_direction(direction) 180 | print(int(direction)) 181 | 182 | if is_quit.is_set(): 183 | break 184 | 185 | pixel_ring.off() 186 | 187 | 188 | if __name__ == '__main__': 189 | # test_4mic() 190 | test_8mic() 191 | -------------------------------------------------------------------------------- /odas.cfg: -------------------------------------------------------------------------------- 1 | # Configuration file for XMOS circular sound card 2 | 3 | version = "2.1"; 4 | 5 | # Raw 6 | 7 | raw: 8 | { 9 | 10 | fS = 16000; 11 | hopSize = 128; 12 | nBits = 32; 13 | nChannels = 4; 14 | 15 | # Input with raw signal from microphones 16 | interface: { 17 | type = "soundcard"; 18 | card = 1; 19 | device = 0; 20 | } 21 | 22 | } 23 | 24 | # Mapping 25 | 26 | mapping: 27 | { 28 | 29 | map: (1, 2, 3, 4); 30 | 31 | } 32 | 33 | # General 34 | 35 | general: 36 | { 37 | 38 | epsilon = 1E-20; 39 | 40 | size: 41 | { 42 | hopSize = 128; 43 | frameSize = 256; 44 | }; 45 | 46 | samplerate: 47 | { 48 | mu = 16000; 49 | sigma2 = 0.01; 50 | }; 51 | 52 | speedofsound: 53 | { 54 | mu = 343.0; 55 | sigma2 = 25.0; 56 | }; 57 | 58 | mics = ( 59 | 60 | # Microphone 1 61 | { 62 | mu = ( -0.0405, +0.0000, +0.0000 ); 63 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 64 | direction = ( +0.000, +0.000, +1.000 ); 65 | angle = ( 80.0, 90.0 ); 66 | }, 67 | 68 | # Microphone 2 69 | { 70 | mu = ( +0.0000, +0.0405, +0.0000 ); 71 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 72 | direction = ( +0.000, +0.000, +1.000 ); 73 | angle = ( 80.0, 90.0 ); 74 | }, 75 | 76 | # Microphone 3 77 | { 78 | mu = ( +0.0405, +0.0000, +0.0000 ); 79 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 80 | direction = ( +0.000, +0.000, +1.000 ); 81 | angle = ( 80.0, 90.0 ); 82 | }, 83 | 84 | # Microphone 4 85 | { 86 | mu = ( +0.0000, -0.0405, +0.0000 ); 87 | sigma2 = ( +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000, +0.000 ); 88 | direction = ( +0.000, +0.000, +1.000 ); 89 | angle = ( 80.0, 90.0 ); 90 | } 91 | 92 | ); 93 | 94 | # Spatial filter to include only a range of direction if required 95 | # (may be useful to remove false detections from the floor) 96 | spatialfilter: { 97 | 98 | direction = ( +0.000, +0.000, +1.000 ); 99 | angle = (80.0, 100.0); 100 | 101 | }; 102 | 103 | nThetas = 181; 104 | gainMin = 0.25; 105 | 106 | }; 107 | 108 | # Stationnary noise estimation 109 | 110 | sne: 111 | { 112 | 113 | b = 3; 114 | alphaS = 0.1; 115 | L = 150; 116 | delta = 3.0; 117 | alphaD = 0.1; 118 | 119 | } 120 | 121 | # Sound Source Localization 122 | 123 | ssl: 124 | { 125 | 126 | nPots = 4; 127 | nMatches = 10; 128 | probMin = 0.5; 129 | nRefinedLevels = 1; 130 | interpRate = 4; 131 | 132 | # Number of scans: level is the resolution of the sphere 133 | # and delta is the size of the maximum sliding window 134 | # (delta = -1 means the size is automatically computed) 135 | scans = ( 136 | { level = 2; delta = -1; }, 137 | { level = 4; delta = -1; } 138 | ); 139 | 140 | # Output to export potential sources 141 | potential: { 142 | 143 | # format = "undefined"; 144 | format = "json"; 145 | 146 | interface: { 147 | # type = "blackhole"; 148 | type = "socket"; ip = "127.0.0.1"; port = 9001; 149 | }; 150 | 151 | }; 152 | 153 | }; 154 | 155 | # Sound Source Tracking 156 | 157 | sst: 158 | { 159 | 160 | # Mode is either "kalman" or "particle" 161 | 162 | mode = "kalman"; 163 | 164 | # Add is either "static" or "dynamic" 165 | 166 | add = "dynamic"; 167 | 168 | # Parameters used by both the Kalman and particle filter 169 | 170 | active = ( 171 | { weight = 1.0; mu = 0.4; sigma2 = 0.0025 } 172 | ); 173 | 174 | inactive = ( 175 | { weight = 1.0; mu = 0.25; sigma2 = 0.0025 } 176 | ); 177 | 178 | sigmaR2_prob = 0.0025; 179 | sigmaR2_active = 0.0225; 180 | sigmaR2_target = 0.0025; 181 | Pfalse = 0.1; 182 | Pnew = 0.1; 183 | Ptrack = 0.8; 184 | 185 | theta_new = 0.9; 186 | N_prob = 5; 187 | theta_prob = 0.8; 188 | N_inactive = ( 250, 250, 250, 250 ); 189 | theta_inactive = 0.9; 190 | 191 | # Parameters used by the Kalman filter only 192 | 193 | kalman: { 194 | 195 | sigmaQ = 0.001; 196 | 197 | }; 198 | 199 | # Parameters used by the particle filter only 200 | 201 | particle: { 202 | 203 | nParticles = 1000; 204 | st_alpha = 2.0; 205 | st_beta = 0.04; 206 | st_ratio = 0.5; 207 | ve_alpha = 0.05; 208 | ve_beta = 0.2; 209 | ve_ratio = 0.3; 210 | ac_alpha = 0.5; 211 | ac_beta = 0.2; 212 | ac_ratio = 0.2; 213 | Nmin = 0.7; 214 | 215 | }; 216 | 217 | target: (); 218 | 219 | # Output to export tracked sources 220 | tracked: { 221 | 222 | format = "json"; 223 | 224 | interface: { 225 | # type = "file"; 226 | # path = "tracks.txt"; 227 | type = "socket"; ip = "127.0.0.1"; port = 9000; 228 | }; 229 | 230 | }; 231 | 232 | } 233 | 234 | sss: 235 | { 236 | 237 | # Mode is either "dds", "dgss" or "dmvdr" 238 | 239 | mode_sep = "dgss"; 240 | mode_pf = "ms"; 241 | 242 | gain_sep = 1.0; 243 | gain_pf = 10.0; 244 | 245 | dds: { 246 | 247 | }; 248 | 249 | dgss: { 250 | 251 | mu = 0.01; 252 | lambda = 0.5; 253 | 254 | }; 255 | 256 | dmvdr: { 257 | 258 | }; 259 | 260 | ms: { 261 | 262 | alphaPmin = 0.07; 263 | eta = 0.5; 264 | alphaZ = 0.8; 265 | thetaWin = 0.3; 266 | alphaWin = 0.3; 267 | maxAbsenceProb = 0.9; 268 | Gmin = 0.01; 269 | winSizeLocal = 3; 270 | winSizeGlobal = 23; 271 | winSizeFrame = 256; 272 | 273 | }; 274 | 275 | ss: { 276 | 277 | Gmin = 0.01; 278 | Gmid = 0.9; 279 | Gslope = 10.0; 280 | 281 | }; 282 | 283 | separated: { 284 | 285 | fS = 16000; 286 | hopSize = 128; 287 | nBits = 16; 288 | 289 | interface: { 290 | type = "file"; 291 | path = "separated.raw"; 292 | }; 293 | 294 | }; 295 | 296 | postfiltered: { 297 | 298 | fS = 16000; 299 | hopSize = 128; 300 | nBits = 16; 301 | gain = 10.0; 302 | 303 | interface: { 304 | type = "file"; 305 | path = "postfiltered.raw"; 306 | }; 307 | 308 | }; 309 | 310 | }; 311 | 312 | classify: 313 | { 314 | 315 | frameSize = 4096; 316 | winSize = 3; 317 | tauMin = 88; 318 | tauMax = 551; 319 | deltaTauMax = 20; 320 | alpha = 0.3; 321 | gamma = 0.05; 322 | phiMin = 0.5; 323 | r0 = 0.2; 324 | 325 | category: { 326 | 327 | format = "undefined"; 328 | 329 | interface: { 330 | type = "blackhole"; 331 | } 332 | 333 | } 334 | 335 | } 336 | -------------------------------------------------------------------------------- /pixel_ring.py: -------------------------------------------------------------------------------- 1 | """ 2 | To control the pixel ring of the ReSpeaker microphone array 3 | Copyright (c) 2016-2017 Seeed Technology Limited. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | """ 17 | 18 | import usb.core 19 | import usb.util 20 | 21 | 22 | class HID: 23 | """ 24 | This class provides basic functions to access 25 | a USB HID device to write an endpoint 26 | """ 27 | 28 | def __init__(self): 29 | self.dev = None 30 | self.ep_in = None 31 | self.ep_out = None 32 | 33 | @staticmethod 34 | def find(vid=0x2886, pid=0x0007): 35 | dev = usb.core.find(idVendor=vid, idProduct=pid) 36 | if not dev: 37 | return 38 | 39 | # get active config 40 | config = dev.get_active_configuration() 41 | 42 | # iterate on all interfaces: 43 | # - if we found a HID interface 44 | interface_number = None 45 | for interface in config: 46 | if interface.bInterfaceClass == 0x03: 47 | interface_number = interface.bInterfaceNumber 48 | break 49 | 50 | try: 51 | if dev.is_kernel_driver_active(interface_number): 52 | dev.detach_kernel_driver(interface_number) 53 | except Exception as e: 54 | print(e.message) 55 | 56 | ep_in, ep_out = None, None 57 | for ep in interface: 58 | if ep.bEndpointAddress & 0x80: 59 | ep_in = ep 60 | else: 61 | ep_out = ep 62 | 63 | if ep_in and ep_out: 64 | hid = HID() 65 | hid.dev = dev 66 | hid.ep_in = ep_in 67 | hid.ep_out = ep_out 68 | 69 | return hid 70 | 71 | def write(self, data): 72 | """ 73 | write data on the OUT endpoint associated to the HID interface 74 | """ 75 | self.ep_out.write(data) 76 | 77 | def read(self): 78 | return self.ep_in.read(self.ep_in.wMaxPacketSize, -1) 79 | 80 | def close(self): 81 | """ 82 | close the interface 83 | """ 84 | usb.util.dispose_resources(self.dev) 85 | 86 | 87 | class PixelRing: 88 | PIXELS_N = 12 89 | 90 | MONO = 1 91 | SPIN = 3 92 | ARC = 5 93 | CUSTOM = 6 94 | 95 | def __init__(self): 96 | self.hid = HID.find() 97 | if not self.hid: 98 | print('No USB device found') 99 | 100 | colors = [0] * 4 * self.PIXELS_N 101 | colors[0] = 0x4 102 | colors[1] = 0x40 103 | colors[2] = 0x4 104 | 105 | colors[4 + 1] = 0x8 106 | colors[4 * 11 + 1] = 0x8 107 | 108 | self.direction_template = colors 109 | 110 | def off(self): 111 | self.set_color(rgb=0) 112 | 113 | def set_color(self, rgb=None, r=0, g=0, b=0): 114 | if rgb: 115 | self.write(0, [self.MONO, rgb & 0xFF, (rgb >> 8) & 0xFF, (rgb >> 16) & 0xFF]) 116 | else: 117 | self.write(0, [self.MONO, b, g, r]) 118 | 119 | def spin(self): 120 | self.write(0, [self.SPIN, 0, 0, 0]) 121 | 122 | def arc(self, pixels): 123 | self.write(0, [self.ARC, 0, 0, pixels]) 124 | 125 | def set_direction(self, angel): 126 | if angel < 0 or angel > 360: 127 | return 128 | 129 | position = int((angel + 15) % 360 / 30) % self.PIXELS_N 130 | colors = self.direction_template[-position*4:] + self.direction_template[:-position*4] 131 | 132 | self.write(0, [self.CUSTOM, 0, 0, 0]) 133 | self.write(3, colors) 134 | 135 | return position 136 | 137 | @staticmethod 138 | def to_bytearray(data): 139 | if type(data) is int: 140 | array = bytearray([data & 0xFF]) 141 | elif type(data) is bytearray: 142 | array = data 143 | elif type(data) is str or type(data) is bytes: 144 | array = bytearray(data) 145 | elif type(data) is list: 146 | array = bytearray(data) 147 | else: 148 | raise TypeError('%s is not supported' % type(data)) 149 | 150 | return array 151 | 152 | def write(self, address, data): 153 | data = self.to_bytearray(data) 154 | length = len(data) 155 | if self.hid: 156 | packet = bytearray([address & 0xFF, (address >> 8) & 0xFF, length & 0xFF, (length >> 8) & 0xFF]) + data 157 | self.hid.write(packet) 158 | 159 | def close(self): 160 | if self.hid: 161 | self.hid.close() 162 | 163 | 164 | pixel_ring = PixelRing() 165 | 166 | 167 | if __name__ == '__main__': 168 | import time 169 | 170 | pixel_ring.spin() 171 | time.sleep(3) 172 | for level in range(4, 8): 173 | pixel_ring.arc(level) 174 | time.sleep(1) 175 | 176 | angel = 0 177 | while True: 178 | try: 179 | pixel_ring.set_direction(angel) 180 | angel = (angel + 30) % 360 181 | time.sleep(1) 182 | except KeyboardInterrupt: 183 | break 184 | 185 | pixel_ring.off() 186 | -------------------------------------------------------------------------------- /vad_doa.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | import webrtcvad 4 | import numpy as np 5 | from mic_array import MicArray 6 | from pixel_ring import pixel_ring 7 | 8 | 9 | RATE = 16000 10 | CHANNELS = 4 11 | VAD_FRAMES = 10 # ms 12 | DOA_FRAMES = 200 # ms 13 | 14 | 15 | def main(): 16 | vad = webrtcvad.Vad(3) 17 | 18 | speech_count = 0 19 | chunks = [] 20 | doa_chunks = int(DOA_FRAMES / VAD_FRAMES) 21 | 22 | try: 23 | with MicArray(RATE, CHANNELS, RATE * VAD_FRAMES / 1000) as mic: 24 | for chunk in mic.read_chunks(): 25 | # Use single channel audio to detect voice activity 26 | if vad.is_speech(chunk[0::CHANNELS].tobytes(), RATE): 27 | speech_count += 1 28 | sys.stdout.write('1') 29 | else: 30 | sys.stdout.write('0') 31 | 32 | sys.stdout.flush() 33 | 34 | chunks.append(chunk) 35 | if len(chunks) == doa_chunks: 36 | if speech_count > (doa_chunks / 2): 37 | frames = np.concatenate(chunks) 38 | direction = mic.get_direction(frames) 39 | pixel_ring.set_direction(direction) 40 | print('\n{}'.format(int(direction))) 41 | 42 | speech_count = 0 43 | chunks = [] 44 | 45 | except KeyboardInterrupt: 46 | pass 47 | 48 | pixel_ring.off() 49 | 50 | 51 | if __name__ == '__main__': 52 | main() 53 | --------------------------------------------------------------------------------