├── LICENSE
├── README.md
├── beatdetect.js
└── fft.js
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | beatdetect
2 | ==========
3 |
4 | Stupid simple port of Minim for Processing's Beat Detector
5 |
6 |
7 | install
8 | -------
9 |
10 | i like submodules so go into your apps 'js' folder:
11 |
12 | ```
13 | git submodule add https://github.com/trippedout/beatdetect.git
14 | ```
15 |
16 | then add to app
17 |
18 | ```
19 |
20 |
21 | ```
22 |
23 | usage
24 | -----
25 |
26 | meant to be used with the an AudioContext in browsers that support it.
27 |
28 | ```
29 | window.AudioContext = window.AudioContext || window.webkitAudioContext;
30 | var audioContext = new AudioContext();
31 | var sampleRate = audioContext.sampleRate;
32 |
33 | // if you create an analyser node with fft size of 2048, your bin count
34 | // will be half that when you get the bin count (1024)
35 |
36 | var analyser = audioContext.createAnalyser();
37 | analyser.fftSize = 2048;
38 |
39 | var beatdetect = new FFT.BeatDetect(analyser.frequencyBinCount, sampleRate);
40 |
41 |
42 | // then inside your onaudioprocess loop you need to grab the
43 | // float time domain data, as opposed to most libs that use
44 | // byte freq data or float freq data
45 | javascriptNode = audioContext.createScriptProcessor(1024, 1, 1);
46 | javascriptNode.onaudioprocess = function()
47 | {
48 | var floats = new Float32Array(analyser.frequencyBinCount);
49 | analyser.getFloatTimeDomainData(floats);
50 |
51 | beatdetect.detect(floats);
52 |
53 | if(beatdetect.isKick() ) console.log("isKick()");
54 | if(beatdetect.isSnare() ) console.log("isSnare()");
55 | }
56 | ```
57 |
58 | implementation notes
59 | --------------------
60 |
61 | disclaimer - i don't write js code day to day (android and c++) so this is garbage. it (surprisingly) does
62 | pretty much what i want it to do (detect beats, duh), but i can definitely use some help. this was thrown
63 | together for a two week (more like 3 day) [project for mashable](https://github.com/trippedout/rackcity), and thus, needs work.
64 |
65 | as noted in the original docs - https://github.com/ddf/Minim/blob/master/src/ddf/minim/analysis/BeatDetect.java
66 | this library is intended for use with more electronic/techno/dance music and might not work as well with super loud
67 | rock and roll/etc.
68 |
69 | using ```analyser.smoothingTimeConstant = 0.85;``` seems to help with the output, so experiment with values here
70 |
71 | there is also a sensitivity variable in beatdetect that i default to 300 - varying this number helps as well, especially making it larger
72 | if you have too many beats being detected in short time spans.
73 |
74 | i'd also love if someone could school me on bower/npm and get this setup for proper usage in apps since not everyone loves submodules
75 |
76 | thanks
77 | ======
78 |
79 | obviously none of this is possible without the great work of the guys at http://code.compartmental.net/ (ddf and co)
80 |
81 |
--------------------------------------------------------------------------------
/beatdetect.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2007 - 2008 by Damien Di Fede
3 | * Copyright (c) 2014 by Anthony Tripaldi
4 | *
5 | * This program is free software; you can redistribute it and/or modify
6 | * it under the terms of the GNU Library General Public License as published
7 | * by the Free Software Foundation; either version 2 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Library General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Library General Public
16 | * License along with this program; if not, write to the Free Software
17 | * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 | */
19 |
20 | FFT.BeatDetect = function(timeSize, sampleRate)
21 | {
22 | var FREQ_ENERGY = 0;
23 | var SOUND_ENERGY = 1;
24 |
25 | var algorithm;
26 | var sampleRate;
27 | var timeSize;
28 | var valCnt;
29 | var valGraph; //float[]
30 | var sensitivity;
31 | // for circular buffer support
32 | var insertAt;
33 | // vars for sEnergy
34 | var isOnset; //bool
35 | var eBuffer;//float[]
36 | var dBuffer;//float[]
37 | var timer;
38 | // vars for fEnergy
39 | var fIsOnset; //bool[]
40 | var spect; //FFT ref
41 | var feBuffer; //float[][]
42 | var fdBuffer; //float[][]
43 | var fTimer; //long[]
44 | var varGraph; //float[]
45 | var varCnt;
46 |
47 | /**
48 | * TODO - add SOUND ENERGY mode back in.
49 | *
50 | * Create a BeatDetect object that is in SOUND_ENERGY mode.
51 | * timeSize
and sampleRate
will be set to 1024
52 | * and 44100, respectively, so that it is possible to switch into FREQ_ENERGY
53 | * mode with meaningful values.
54 | *
55 | */
56 | // BeatDetect()
57 | // {
58 | // sampleRate = 44100;
59 | // timeSize = 1024;
60 | // initSEResources();
61 | // initGraphs();
62 | // algorithm = SOUND_ENERGY;
63 | // sensitivity = 10;
64 | // }
65 |
66 | /**
67 | * Create a BeatDetect object that is in FREQ_ENERGY mode and expects a
68 | * sample buffer with the requested attributes.
69 | *
70 | * @param timeSize
71 | * int: the size of the buffer
72 | * @param sampleRate
73 | * float: the sample rate of the samples in the buffer
74 | *
75 | * @related BeatDetect
76 | */
77 | // BeatDetect(int timeSize, float sampleRate)
78 | // {
79 | this.sampleRate = sampleRate;
80 | this.timeSize = timeSize;
81 | initFEResources();
82 | initGraphs();
83 | algorithm = FREQ_ENERGY;
84 | sensitivity = 225;
85 | // }
86 |
87 | /**
88 | * Set the object to use the requested algorithm. If an invalid value is
89 | * passed, the function will report and error and default to
90 | * BeatDetect.SOUND_ENERGY
91 | *
92 | * @param algo
93 | * int: either BeatDetect.SOUND_ENERGY or BeatDetect.FREQ_ENERGY
94 | *
95 | * @related BeatDetect
96 | */
97 | function detectMode(algo)
98 | {
99 | if (algo < 0 || algo > 1)
100 | {
101 | Minim.error("Unrecognized detect mode, defaulting to SOUND_ENERGY.");
102 | algo = SOUND_ENERGY;
103 | }
104 | if (algo == SOUND_ENERGY)
105 | {
106 | if (algorithm == FREQ_ENERGY)
107 | {
108 | releaseFEResources();
109 | initSEResources();
110 | initGraphs();
111 | algorithm = algo;
112 | }
113 | }
114 | else
115 | {
116 | if (algorithm == SOUND_ENERGY)
117 | {
118 | releaseSEResources();
119 | initFEResources();
120 | initGraphs();
121 | algorithm = FREQ_ENERGY;
122 | }
123 | }
124 | }
125 |
126 | function initGraphs()
127 | {
128 | valCnt = varCnt = 0;
129 | valGraph = new Float32Array(512);
130 | varGraph = new Float32Array(512);
131 | }
132 |
133 | function initSEResources()
134 | {
135 | isOnset = false;
136 | eBuffer = new float[sampleRate / timeSize];
137 | dBuffer = new float[sampleRate / timeSize];
138 | timer = Date.now();
139 | insertAt = 0;
140 | }
141 |
142 | function initFEResources()
143 | {
144 | spect = new FFT.fft(timeSize, sampleRate);
145 | spect.logAverages(60, 3);
146 | var numAvg = spect.avgSize();
147 | fIsOnset = new Array(numAvg);
148 |
149 | feBuffer = new Array(numAvg);
150 | for(var i = 0; i < feBuffer.length; i++) feBuffer[i] = new Float32Array(sampleRate / timeSize);
151 |
152 | fdBuffer = new Array(numAvg);
153 | for(i = 0; i < fdBuffer.length; i++) fdBuffer[i] = new Float32Array(sampleRate / timeSize);
154 |
155 | fTimer = new Array(numAvg);
156 | var start = Date.now();;
157 | for (var i = 0; i < fTimer.length; i++)
158 | {
159 | fTimer[i] = start;
160 | }
161 | insertAt = 0;
162 | }
163 |
164 | function releaseSEResources()
165 | {
166 | isOnset = false;
167 | eBuffer = null;
168 | dBuffer = null;
169 | timer = 0;
170 | }
171 |
172 | function releaseFEResources()
173 | {
174 | spect = null;
175 | fIsOnset = null;
176 | feBuffer = null;
177 | fdBuffer = null;
178 | fTimer = null;
179 | }
180 |
181 | /**
182 | * Analyze the samples in buffer
.
183 | * This is a cumulative process, so you must call this function every frame.
184 | *
185 | * @param buffer
186 | * AudioBuffer: the buffer to analyze.
187 | *
188 | * @example Analysis/SoundEnergyBeatDetection
189 | *
190 | * @related BeatDetect
191 | */
192 | // function detect(AudioBuffer buffer)
193 | // {
194 | // detect( buffer.toArray() );
195 | // }
196 |
197 |
198 | /**
199 | * Analyze the samples in buffer
. This is a cumulative
200 | * process, so you must call this function every frame.
201 | *
202 | * @param buffer
203 | * float[]: the buffer to analyze
204 | *
205 | * @related BeatDetect
206 | */
207 | this.detect = function(buffer) //float[]
208 | {
209 | switch (algorithm)
210 | {
211 | case SOUND_ENERGY:
212 | sEnergy(buffer);
213 | break;
214 | case FREQ_ENERGY:
215 | fEnergy(buffer);
216 | break;
217 | }
218 | }
219 |
220 | /**
221 | * In frequency energy mode this returns the number of frequency bands
222 | * currently being used. In sound energy mode this always returns 0.
223 | *
224 | * @return int: the length of the FFT's averages array
225 | *
226 | * @related BeatDetect
227 | */
228 | function dectectSize()
229 | {
230 | if ( algorithm == FREQ_ENERGY )
231 | {
232 | return spect.avgSize();
233 | }
234 |
235 | return 0;
236 | }
237 |
238 | /**
239 | * Returns the center frequency of the ith frequency band.
240 | * In sound energy mode this always returns 0.
241 | *
242 | * @param i
243 | * int: which detect band you want the center frequency of.
244 | *
245 | * @return float: the center frequency of the ith frequency band
246 | *
247 | * @related BeatDetect
248 | */
249 | function getDetectCenterFrequency(i)
250 | {
251 | if ( algorithm == FREQ_ENERGY )
252 | {
253 | return spect.getAverageCenterFrequency(i);
254 | }
255 |
256 | return 0;
257 | }
258 |
259 | /**
260 | * Sets the sensitivity of the algorithm. After a beat has been detected, the
261 | * algorithm will wait for millis
milliseconds before allowing
262 | * another beat to be reported. You can use this to dampen the algorithm if
263 | * it is giving too many false-positives. The default value is 10, which is
264 | * essentially no damping. If you try to set the sensitivity to a negative
265 | * value, an error will be reported and it will be set to 10 instead.
266 | *
267 | * @param millis
268 | * int: the sensitivity in milliseconds
269 | *
270 | * @example Analysis/FrequencyEnergyBeatDetection
271 | *
272 | * @related BeatDetect
273 | */
274 | this.setSensitivity = function(millis)
275 | {
276 | if (millis < 0)
277 | {
278 | Minim.error("BeatDetect: sensitivity cannot be less than zero. Defaulting to 10.");
279 | sensitivity = 300;
280 | }
281 | else
282 | {
283 | sensitivity = millis;
284 | }
285 | }
286 |
287 | /**
288 | * In sound energy mode this returns true when a beat has been detected. In
289 | * frequency energy mode this always returns false.
290 | *
291 | * @return boolean: true if a beat has been detected.
292 | *
293 | * @example Analysis/SoundEnergyBeatDetection
294 | *
295 | * @related BeatDetect
296 | */
297 | function isOnset()
298 | {
299 | return isOnset;
300 | }
301 |
302 | /**
303 | * In frequency energy mode this returns true when a beat has been detect in
304 | * the ith
frequency band. In sound energy mode
305 | * this always returns false.
306 | *
307 | * @param i
308 | * int: the frequency band to query
309 | * @return boolean: true if a beat has been detected in the requested band
310 | *
311 | * @example Analysis/SoundEnergyBeatDetection
312 | *
313 | * @related BeatDetect
314 | */
315 | function isOnset(i)
316 | {
317 | if (algorithm == SOUND_ENERGY)
318 | {
319 | return false;
320 | }
321 | return fIsOnset[i];
322 | }
323 |
324 | /**
325 | * In frequency energy mode this returns true if a beat corresponding to the
326 | * frequency range of a kick drum has been detected. This has been tuned to
327 | * work well with dance / techno music and may not perform well with other
328 | * styles of music. In sound energy mode this always returns false.
329 | *
330 | * @return boolean: true if a kick drum beat has been detected
331 | *
332 | * @example Analysis/FrequencyEnergyBeatDetection
333 | *
334 | * @related BeatDetect
335 | */
336 | this.isKick = function()
337 | {
338 | if (algorithm == SOUND_ENERGY)
339 | {
340 | return false;
341 | }
342 | var upper = 6 >= spect.avgSize() ? spect.avgSize() : 6;
343 | return isRange(1, upper, 2);
344 | }
345 |
346 | /**
347 | * In frequency energy mode this returns true if a beat corresponding to the
348 | * frequency range of a snare drum has been detected. This has been tuned to
349 | * work well with dance / techno music and may not perform well with other
350 | * styles of music. In sound energy mode this always returns false.
351 | *
352 | * @return boolean: true if a snare drum beat has been detected
353 | *
354 | * @example Analysis/FrequencyEnergyBeatDetection
355 | *
356 | * @related BeatDetect
357 | */
358 | this.isSnare = function()
359 | {
360 | if (algorithm == SOUND_ENERGY)
361 | {
362 | return false;
363 | }
364 | var lower = 8 >= spect.avgSize() ? spect.avgSize() : 8;
365 | var upper = spect.avgSize() - 1;
366 | var thresh = (upper - lower) / 3 + 1;
367 | return isRange(lower, upper, thresh);
368 | }
369 |
370 | /**
371 | * In frequency energy mode this returns true if a beat corresponding to the
372 | * frequency range of a hi hat has been detected. This has been tuned to work
373 | * well with dance / techno music and may not perform well with other styles
374 | * of music. In sound energy mode this always returns false.
375 | *
376 | * @return boolean: true if a hi hat beat has been detected
377 | *
378 | * @example Analysis/FrequencyEnergyBeatDetection
379 | *
380 | * @related BeatDetect
381 | */
382 | function isHat()
383 | {
384 | if (algorithm == SOUND_ENERGY)
385 | {
386 | return false;
387 | }
388 | var lower = spect.avgSize() - 7 < 0 ? 0 : spect.avgSize() - 7;
389 | var upper = spect.avgSize() - 1;
390 | return isRange(lower, upper, 1);
391 | }
392 |
393 | /**
394 | * In frequency energy mode this returns true if at least
395 | * threshold
bands of the bands included in the range
396 | * [low, high]
have registered a beat. In sound energy mode
397 | * this always returns false.
398 | *
399 | * @param low
400 | * int: the index of the lower band
401 | * @param high
402 | * int: the index of the higher band
403 | * @param threshold
404 | * int: the smallest number of bands in the range
405 | * [low, high]
that need to have registered a beat
406 | * for this to return true
407 | * @return boolean: true if at least threshold
bands of the bands
408 | * included in the range [low, high]
have registered a
409 | * beat
410 | *
411 | * @related BeatDetect
412 | */
413 | function isRange(low, high, threshold)
414 | {
415 | if (algorithm == SOUND_ENERGY)
416 | {
417 | return false;
418 | }
419 | var num = 0;
420 | for (var i = low; i < high + 1; i++)
421 | {
422 | if (isOnset(i))
423 | {
424 | num++;
425 | }
426 | }
427 | return num >= threshold;
428 | }
429 |
430 | /**
431 | * Draws some debugging visuals in the passed PApplet. The visuals drawn when
432 | * in frequency energy mode are a good way to determine what values to use
433 | * with inRange()
if the provided drum detecting functions
434 | * aren't what you need or aren't working well.
435 | *
436 | * @param p
437 | * the PApplet to draw in
438 | */
439 | // function drawGraph(PApplet p)
440 | // {
441 | // if (algorithm == SOUND_ENERGY)
442 | // {
443 | // // draw valGraph
444 | // for (int i = 0; i < valCnt; i++)
445 | // {
446 | // p.stroke(255);
447 | // p.line(i, (p.height / 2) - valGraph[i], i, (p.height / 2)
448 | // + valGraph[i]);
449 | // }
450 | // // draw varGraph
451 | // for (int i = 0; i < varCnt - 1; i++)
452 | // {
453 | // p.stroke(255);
454 | // p.line(i, p.height - varGraph[i], i + 1, p.height - varGraph[i + 1]);
455 | // }
456 | // }
457 | // else
458 | // {
459 | // p.strokeWeight(5);
460 | // for (int i = 0; i < fTimer.length; i++)
461 | // {
462 | // int c = (i % 3 == 0) ? p.color(255, 0, 0) : p.color(255);
463 | // p.stroke(c);
464 | // long clock = Date.now();
465 | // if (clock - fTimer[i] < sensitivity)
466 | // {
467 | // float h = PApplet.map(clock - fTimer[i], 0, sensitivity, 100, 0);
468 | // p.line((i * 10), p.height - h, (i * 10), p.height);
469 | // }
470 | // }
471 | // }
472 | // }
473 |
474 | // function sEnergy(samples) //float[]
475 | // {
476 | // // compute the energy level
477 | // float level = 0;
478 | // for (int i = 0; i < samples.length; i++)
479 | // {
480 | // level += (samples[i] * samples[i]);
481 | // }
482 | // level /= samples.length;
483 | // level = (float) Math.sqrt(level);
484 | // float instant = level * 100;
485 | // // compute the average local energy
486 | // float E = average(eBuffer);
487 | // // compute the variance of the energies in eBuffer
488 | // float V = variance(eBuffer, E);
489 | // // compute C using a linear digression of C with V
490 | // float C = (-0.0025714f * V) + 1.5142857f;
491 | // // filter negaive values
492 | // float diff = (float)Math.max(instant - C * E, 0);
493 | // pushVal(diff);
494 | // // find the average of only the positive values in dBuffer
495 | // float dAvg = specAverage(dBuffer);
496 | // // filter negative values
497 | // float diff2 = (float)Math.max(diff - dAvg, 0);
498 | // pushVar(diff2);
499 | // // report false if it's been less than 'sensitivity'
500 | // // milliseconds since the last true value
501 | // if (Date.now() - timer < sensitivity)
502 | // {
503 | // isOnset = false;
504 | // }
505 | // // if we've made it this far then we're allowed to set a new
506 | // // value, so set it true if it deserves to be, restart the timer
507 | // else if (diff2 > 0 && instant > 2)
508 | // {
509 | // isOnset = true;
510 | // timer = Date.now();
511 | // }
512 | // // OMG it wasn't true!
513 | // else
514 | // {
515 | // isOnset = false;
516 | // }
517 | // eBuffer[insertAt] = instant;
518 | // dBuffer[insertAt] = diff;
519 | // insertAt++;
520 | // if (insertAt == eBuffer.length)
521 | // insertAt = 0;
522 | // }
523 |
524 | function fEnergy(float_in)//float[]
525 | {
526 | spect.forward(float_in);
527 |
528 | var instant, E, V, C, diff, dAvg, diff2;
529 | for (var i = 0; i < feBuffer.length; i++)
530 | {
531 | instant = spect.getAvg(i);
532 | // console.log(instant);
533 | E = average(feBuffer[i]);
534 | V = variance(feBuffer[i], E);
535 | C = (-0.0025714 * V) + 1.5142857;
536 | diff = Math.max(instant - C * E, 0);
537 | dAvg = specAverage(fdBuffer[i]);
538 | diff2 = Math.max(diff - dAvg, 0);
539 | if (Date.now() - fTimer[i] < sensitivity)
540 | {
541 | fIsOnset[i] = false;
542 | }
543 | else if (diff2 > 0)
544 | {
545 | fIsOnset[i] = true;
546 | fTimer[i] = Date.now();
547 | }
548 | else
549 | {
550 | fIsOnset[i] = false;
551 | }
552 | feBuffer[i][insertAt] = instant;
553 | fdBuffer[i][insertAt] = diff;
554 | }
555 | insertAt++;
556 | if (insertAt == feBuffer[0].length)
557 | {
558 | insertAt = 0;
559 | }
560 | }
561 |
562 | function pushVal(v)
563 | {
564 | // println(valCnt);
565 | if (valCnt == valGraph.length)
566 | {
567 | valCnt = 0;
568 | valGraph = new Float32Array(valGraph.length);
569 | }
570 | valGraph[valCnt] = v;
571 | valCnt++;
572 | }
573 |
574 | function pushVar(v)
575 | {
576 | // println(valCnt);
577 | if (varCnt == varGraph.length)
578 | {
579 | varCnt = 0;
580 | varGraph = new Float32Array(varGraph.length);
581 | }
582 | varGraph[varCnt] = v;
583 | varCnt++;
584 | }
585 |
586 | function average(arr) //float[]
587 | {
588 | var avg = 0;
589 | for (var i = 0; i < arr.length; i++)
590 | {
591 | avg += arr[i];
592 | }
593 | avg /= arr.length;
594 | return avg;
595 | }
596 |
597 | function specAverage(arr) //float[]
598 | {
599 | var avg = 0;
600 | var num = 0;
601 | for (var i = 0; i < arr.length; i++)
602 | {
603 | if (arr[i] > 0)
604 | {
605 | avg += arr[i];
606 | num++;
607 | }
608 | }
609 | if (num > 0)
610 | {
611 | avg /= num;
612 | }
613 | return avg;
614 | }
615 |
616 | function variance(arr, val) //float[] float
617 | {
618 | var V = 0;
619 | for (var i = 0; i < arr.length; i++)
620 | {
621 | V += Math.pow(arr[i] - val, 2);
622 | }
623 | V /= arr.length;
624 | return V;
625 | }
626 | };
--------------------------------------------------------------------------------
/fft.js:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2007 - 2008 by Damien Di Fede
3 | * Copyright (c) 2014 by Anthony Tripaldi
4 | *
5 | * This program is free software; you can redistribute it and/or modify
6 | * it under the terms of the GNU Library General Public License as published
7 | * by the Free Software Foundation; either version 2 of the License, or
8 | * (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Library General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Library General Public
16 | * License along with this program; if not, write to the Free Software
17 | * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 | */
19 |
20 | 'use strict';
21 | var FFT = { REVISION:"0.1.0" };
22 |
23 | FFT.fft = function ( ts, sr )
24 | {
25 | console.log("FFT.fft() " + ts, sr);
26 |
27 | var LINAVG = 1;
28 | var LOGAVG = 2;
29 | var NOAVG = 3;
30 |
31 | var TWO_PI = (2 * Math.PI);
32 | var timeSize;
33 | var sampleRate;
34 | var bandWidth;
35 | // WindowFunction currentWindow;
36 | var real = [];
37 | var imag = [];
38 | var spectrum = [];
39 | var averages = [];
40 | var whichAverage;
41 | var octaves;
42 | var avgPerOctave;
43 |
44 | /**
45 | * Construct a FourierTransform that will analyze sample buffers that are
46 | * ts
samples long and contain samples with a sr
47 | * sample rate.
48 | *
49 | * @param ts
50 | * the length of the buffers that will be analyzed
51 | * @param sr
52 | * the sample rate of the samples that will be analyzed
53 | */
54 |
55 | // FourierTransform(ts,sr)
56 | // {
57 | timeSize = ts;
58 | sampleRate = sr;
59 | bandWidth = (2 / timeSize) * (sampleRate / 2);
60 | noAverages();
61 | allocateArrays();
62 | //currentWindow = new RectangularWindow(); // current window calls apply and shit at the bottom
63 | // }
64 |
65 | /*
66 | function setComplex(float[] r, float[] i)
67 | {
68 | if (real.length != r.length && imag.length != i.length)
69 | {
70 | Minim
71 | .error("FourierTransform.setComplex: the two arrays must be the same length as their member counterparts.");
72 | }
73 | else
74 | {
75 | System.arraycopy(r, 0, real, 0, r.length);
76 | System.arraycopy(i, 0, imag, 0, i.length);
77 | }
78 | }
79 | */
80 | function fillSpectrum()
81 | {
82 |
83 | for (var i = 0; i < spectrum.length; i++)
84 | {
85 | spectrum[i] = Math.sqrt(real[i] * real[i] + imag[i] * imag[i]);
86 | }
87 |
88 | // console.log(spectrum[0]);
89 |
90 | if (whichAverage == LINAVG)
91 | {
92 | var avgWidth = spectrum.length / averages.length;
93 | for (var i = 0; i < averages.length; i++)
94 | {
95 | var avg = 0;
96 | var j;
97 | for (j = 0; j < avgWidth; j++)
98 | {
99 | var offset = j + i * avgWidth;
100 | if (offset < spectrum.length)
101 | {
102 | avg += spectrum[offset];
103 | }
104 | else
105 | {
106 | break;
107 | }
108 | }
109 | avg /= j + 1;
110 | averages[i] = avg;
111 | }
112 | }
113 | else if (whichAverage == LOGAVG)
114 | {
115 | for (var i = 0; i < octaves; i++)
116 | {
117 | var lowFreq, hiFreq, freqStep;
118 | if (i == 0)
119 | {
120 | lowFreq = 0;
121 | }
122 | else
123 | {
124 | lowFreq = (sampleRate / 2) / Math.pow(2, octaves - i);
125 | }
126 | hiFreq = (sampleRate / 2) / Math.pow(2, octaves - i - 1);
127 | freqStep = (hiFreq - lowFreq) / avgPerOctave;
128 | var f = lowFreq;
129 | for (var j = 0; j < avgPerOctave; j++)
130 | {
131 | var offset = j + i * avgPerOctave;
132 | averages[offset] = calcAvg(f, f + freqStep);
133 | f += freqStep;
134 | }
135 | }
136 | }
137 | }
138 |
139 |
140 | function noAverages()
141 | {
142 | averages = new Float32Array(0);
143 | whichAverage = NOAVG;
144 | }
145 | /*
146 | function linAverages(var numAvg)
147 | {
148 | if (numAvg > spectrum.length / 2)
149 | {
150 | Minim.error("The number of averages for this transform can be at most "
151 | + spectrum.length / 2 + ".");
152 | return;
153 | }
154 | else
155 | {
156 | averages = new float[numAvg];
157 | }
158 | whichAverage = LINAVG;
159 | }
160 | */
161 | this.logAverages = function(minBandwidth, bandsPerOctave)
162 | {
163 | var nyq = sampleRate / 2;
164 | octaves = 1;
165 | while ((nyq /= 2) > minBandwidth)
166 | {
167 | octaves++;
168 | }
169 |
170 | console.log("Number of octaves = " + octaves);
171 |
172 | avgPerOctave = bandsPerOctave;
173 | averages = new Float32Array(octaves * bandsPerOctave);
174 | whichAverage = LOGAVG;
175 | }
176 |
177 | /*
178 | function window(WindowFunction windowFunction)
179 | {
180 | this.currentWindow = windowFunction;
181 | }
182 |
183 | */
184 |
185 | function doWindow(samples) //float[]
186 | {
187 | apply(samples);
188 | }
189 |
190 | /*
191 | function timeSize()
192 | {
193 | return timeSize;
194 | }
195 |
196 | function specSize()
197 | {
198 | return spectrum.length;
199 | }
200 |
201 | function getBand(i)
202 | {
203 | if (i < 0) i = 0;
204 | if (i > spectrum.length - 1) i = spectrum.length - 1;
205 | return spectrum[i];
206 | }
207 | */
208 | function getBandWidth()
209 | {
210 | return bandWidth;
211 | }
212 | /*
213 | function getAverageBandWidth( averageIndex )
214 | {
215 | if ( whichAverage == LINAVG )
216 | {
217 | // an average represents a certain number of bands in the spectrum
218 | var avgWidth = (int) spectrum.length / averages.length;
219 | return avgWidth * getBandWidth();
220 |
221 | }
222 | else if ( whichAverage == LOGAVG )
223 | {
224 | // which "octave" is this index in?
225 | var octave = averageIndex / avgPerOctave;
226 | float lowFreq, hiFreq, freqStep;
227 | // figure out the low frequency for this octave
228 | if (octave == 0)
229 | {
230 | lowFreq = 0;
231 | }
232 | else
233 | {
234 | lowFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave);
235 | }
236 | // and the high frequency for this octave
237 | hiFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave - 1);
238 | // each average band within the octave will be this big
239 | freqStep = (hiFreq - lowFreq) / avgPerOctave;
240 |
241 | return freqStep;
242 | }
243 |
244 | return 0;
245 | }
246 | */
247 | function freqToIndex(freq)
248 | {
249 | // special case: freq is lower than the bandwidth of spectrum[0]
250 | if (freq < getBandWidth() / 2) return 0;
251 | // special case: freq is within the bandwidth of spectrum[spectrum.length - 1]
252 | if (freq > sampleRate / 2 - getBandWidth() / 2) return spectrum.length - 1;
253 | // all other cases
254 | var fraction = freq / sampleRate;
255 | var i = Math.round(timeSize * fraction);
256 | return i;
257 | }
258 | /*
259 | function indexToFreq(i)
260 | {
261 | float bw = getBandWidth();
262 | // special case: the width of the first bin is half that of the others.
263 | // so the center frequency is a quarter of the way.
264 | if ( i == 0 ) return bw * 0.25f;
265 | // special case: the width of the last bin is half that of the others.
266 | if ( i == spectrum.length - 1 )
267 | {
268 | float lastBinBeginFreq = (sampleRate / 2) - (bw / 2);
269 | float binHalfWidth = bw * 0.25f;
270 | return lastBinBeginFreq + binHalfWidth;
271 | }
272 | // the center frequency of the ith band is simply i*bw
273 | // because the first band is half the width of all others.
274 | // treating it as if it wasn't offsets us to the middle
275 | // of the band.
276 | return i*bw;
277 | }
278 |
279 | function getAverageCenterFrequency(i)
280 | {
281 | if ( whichAverage == LINAVG )
282 | {
283 | // an average represents a certain number of bands in the spectrum
284 | var avgWidth = (int) spectrum.length / averages.length;
285 | // the "center" bin of the average, this is fudgy.
286 | var centerBinIndex = i*avgWidth + avgWidth/2;
287 | return indexToFreq(centerBinIndex);
288 |
289 | }
290 | else if ( whichAverage == LOGAVG )
291 | {
292 | // which "octave" is this index in?
293 | var octave = i / avgPerOctave;
294 | // which band within that octave is this?
295 | var offset = i % avgPerOctave;
296 | float lowFreq, hiFreq, freqStep;
297 | // figure out the low frequency for this octave
298 | if (octave == 0)
299 | {
300 | lowFreq = 0;
301 | }
302 | else
303 | {
304 | lowFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave);
305 | }
306 | // and the high frequency for this octave
307 | hiFreq = (sampleRate / 2) / (float) Math.pow(2, octaves - octave - 1);
308 | // each average band within the octave will be this big
309 | freqStep = (hiFreq - lowFreq) / avgPerOctave;
310 | // figure out the low frequency of the band we care about
311 | float f = lowFreq + offset*freqStep;
312 | // the center of the band will be the low plus half the width
313 | return f + freqStep/2;
314 | }
315 |
316 | return 0;
317 | }
318 |
319 |
320 | float getFreq(float freq)
321 | {
322 | return getBand(freqToIndex(freq));
323 | }
324 |
325 | function setFreq(float freq, float a)
326 | {
327 | setBand(freqToIndex(freq), a);
328 | }
329 |
330 | function scaleFreq(float freq, float s)
331 | {
332 | scaleBand(freqToIndex(freq), s);
333 | }
334 | */
335 | this.avgSize = function()
336 | {
337 | return averages.length;
338 | }
339 |
340 | this.getAvg = function(i)
341 | {
342 | var ret;
343 |
344 | if (averages.length > 0)
345 | ret = averages[i];
346 | else
347 | ret = 0;
348 |
349 | return ret;
350 | }
351 |
352 | function calcAvg(lowFreq, hiFreq)
353 | {
354 | var lowBound = freqToIndex(lowFreq);
355 | var hiBound = freqToIndex(hiFreq);
356 | var avg = 0;
357 |
358 | for (var i = lowBound; i <= hiBound; i++)
359 | {
360 | avg += spectrum[i];
361 | }
362 |
363 |
364 |
365 | avg /= (hiBound - lowBound + 1);
366 |
367 | return avg;
368 | }
369 |
370 | /*
371 | float[] getSpectrumReal()
372 | {
373 | return real;
374 | }
375 |
376 | float[] getSpectrumImaginary()
377 | {
378 | return imag;
379 | }
380 | /*
381 |
382 | function forward(float[] buffer, var startAt)
383 | {
384 | if ( buffer.length - startAt < timeSize )
385 | {
386 | Minim.error( "FourierTransform.forward: not enough samples in the buffer between " +
387 | startAt + " and " + buffer.length + " to perform a transform."
388 | );
389 | return;
390 | }
391 |
392 | // copy the section of samples we want to analyze
393 | float[] section = new float[timeSize];
394 | System.arraycopy(buffer, startAt, section, 0, section.length);
395 | forward(section);
396 | }
397 |
398 | function forward(AudioBuffer buffer)
399 | {
400 | forward(buffer.toArray());
401 | }
402 |
403 | function forward(AudioBuffer buffer, var startAt)
404 | {
405 | forward(buffer.toArray(), startAt);
406 | }
407 |
408 | abstract function inverse(float[] buffer);
409 |
410 | function inverse(AudioBuffer buffer)
411 | {
412 | inverse(buffer.toArray());
413 | }
414 |
415 | function inverse(float[] freqReal, float[] freqImag, float[] buffer)
416 | {
417 | setComplex(freqReal, freqImag);
418 | inverse(buffer);
419 | }
420 | */
421 |
422 | // ----------------------------------------------------------------------------------------
423 |
424 | // FFT CLASS with overides
425 |
426 | // ----------------------------------------------------------------------------------------
427 |
428 | //constructor - this is called when u create new shit, super handles the rest
429 | // FFT(int timeSize, float sampleRate)
430 | // {
431 | // super(timeSize, sampleRate);
432 | // if ((timeSize & (timeSize - 1)) != 0)
433 | // {
434 | // throw new IllegalArgumentException("FFT: timeSize must be a power of two.");
435 | // }
436 | buildReverseTable();
437 | buildTrigTables();
438 | // }
439 |
440 | function allocateArrays()
441 | {
442 | spectrum = new Float32Array(timeSize / 2 + 1);
443 | real = new Float32Array(timeSize);
444 | imag = new Float32Array(timeSize);
445 | }
446 |
447 | /*
448 | function scaleBand(int i, float s)
449 | {
450 | if (s < 0)
451 | {
452 | Minim.error("Can't scale a frequency band by a negative value.");
453 | return;
454 | }
455 |
456 | real[i] *= s;
457 | imag[i] *= s;
458 | spectrum[i] *= s;
459 |
460 | if (i != 0 && i != timeSize / 2)
461 | {
462 | real[timeSize - i] = real[i];
463 | imag[timeSize - i] = -imag[i];
464 | }
465 | }
466 |
467 | function setBand(int i, float a)
468 | {
469 | if (a < 0)
470 | {
471 | Minim.error("Can't set a frequency band to a negative value.");
472 | return;
473 | }
474 | if (real[i] == 0 && imag[i] == 0)
475 | {
476 | real[i] = a;
477 | spectrum[i] = a;
478 | }
479 | else
480 | {
481 | real[i] /= spectrum[i];
482 | imag[i] /= spectrum[i];
483 | spectrum[i] = a;
484 | real[i] *= spectrum[i];
485 | imag[i] *= spectrum[i];
486 | }
487 | if (i != 0 && i != timeSize / 2)
488 | {
489 | real[timeSize - i] = real[i];
490 | imag[timeSize - i] = -imag[i];
491 | }
492 | }
493 | */
494 |
495 | // performs an in-place fft on the data in the real and imag arrays
496 | // bit reversing is not necessary as the data will already be bit reversed
497 | function fft()
498 | {
499 | for (var halfSize = 1; halfSize < real.length; halfSize *= 2)
500 | {
501 | // float k = -(float)Math.PI/halfSize;
502 | // phase shift step
503 | // float phaseShiftStepR = (float)Math.cos(k);
504 | // float phaseShiftStepI = (float)Math.sin(k);
505 | // using lookup table
506 | var phaseShiftStepR = cos(halfSize);
507 | var phaseShiftStepI = sin(halfSize);
508 | // current phase shift
509 | var currentPhaseShiftR = 1.0;
510 | var currentPhaseShiftI = 0.0;
511 | for (var fftStep = 0; fftStep < halfSize; fftStep++)
512 | {
513 | for (var i = fftStep; i < real.length; i += 2 * halfSize)
514 | {
515 | var off = i + halfSize;
516 | var tr = (currentPhaseShiftR * real[off]) - (currentPhaseShiftI * imag[off]);
517 | var ti = (currentPhaseShiftR * imag[off]) + (currentPhaseShiftI * real[off]);
518 | real[off] = real[i] - tr;
519 | imag[off] = imag[i] - ti;
520 | real[i] += tr;
521 | imag[i] += ti;
522 | }
523 | var tmpR = currentPhaseShiftR;
524 | currentPhaseShiftR = (tmpR * phaseShiftStepR) - (currentPhaseShiftI * phaseShiftStepI);
525 | currentPhaseShiftI = (tmpR * phaseShiftStepI) + (currentPhaseShiftI * phaseShiftStepR);
526 | }
527 | }
528 | }
529 |
530 |
531 | this.forward = function(buffer) //float[]
532 | {
533 | if (buffer.length != timeSize)
534 | {
535 | console.log("FFT.forward: The length of the passed sample buffer must be equal to timeSize().");
536 | return;
537 | }
538 |
539 | doWindow(buffer);
540 |
541 | // copy samples to real/imag in bit-reversed order
542 | bitReverseSamples(buffer, 0);
543 | // perform the fft
544 | fft();
545 | // fill the spectrum buffer with amplitudes
546 | fillSpectrum();
547 | }
548 |
549 | // function forward(buffer, startAt) //float[]
550 | // {
551 | // if ( buffer.length - startAt < timeSize )
552 | // {
553 | // Minim.error( "FourierTransform.forward: not enough samples in the buffer between " +
554 | // startAt + " and " + buffer.length + " to perform a transform."
555 | // );
556 | // return;
557 | // }
558 |
559 | // currentWindow.apply( buffer, startAt, timeSize );
560 | // bitReverseSamples(buffer, startAt);
561 | // fft();
562 | // fillSpectrum();
563 | // }
564 |
565 | // function forward(buffReal, buffImag) //float[] float[]
566 | // {
567 | // if (buffReal.length != timeSize || buffImag.length != timeSize)
568 | // {
569 | // console.log("FFT.forward: The length of the passed buffers must be equal to timeSize().");
570 | // return;
571 | // }
572 | // setComplex(buffReal, buffImag);
573 | // bitReverseComplex();
574 | // fft();
575 | // fillSpectrum();
576 | // }
577 | /*
578 | function inverse(buffer) //float[]
579 | {
580 | if (buffer.length > real.length)
581 | {
582 | Minim
583 | .error("FFT.inverse: the passed array's length must equal FFT.timeSize().");
584 | return;
585 | }
586 | // conjugate
587 | for (var i = 0; i < timeSize; i++)
588 | {
589 | imag[i] *= -1;
590 | }
591 | bitReverseComplex();
592 | fft();
593 | // copy the result in real into buffer, scaling as we do
594 | for (var i = 0; i < buffer.length; i++)
595 | {
596 | buffer[i] = real[i] / real.length;
597 | }
598 | }
599 |
600 | */
601 | var reverse;
602 |
603 | function buildReverseTable()
604 | {
605 | var N = timeSize;
606 | reverse = new Array(N);
607 |
608 | // set up the bit reversing table
609 | reverse[0] = 0;
610 | for (var limit = 1, bit = N / 2; limit < N; limit <<= 1, bit >>= 1)
611 | for (var i = 0; i < limit; i++)
612 | reverse[i + limit] = reverse[i] + bit;
613 |
614 | }
615 |
616 | // copies the values in the samples array into the real array
617 | // in bit reversed order. the imag array is filled with zeros.
618 | function bitReverseSamples(samples, startAt) //float[] int
619 | {
620 | for (var i = 0; i < timeSize; ++i)
621 | {
622 | real[i] = samples[ startAt + reverse[i] ];
623 | imag[i] = 0.0;
624 | }
625 | }
626 |
627 | // bit reverse real[] and imag[]
628 | function bitReverseComplex()
629 | {
630 | var revReal = new Float32Array(real.length);
631 | var revImag = new Float32Array(imag.length);
632 | for (var i = 0; i < real.length; i++)
633 | {
634 | revReal[i] = real[reverse[i]];
635 | revImag[i] = imag[reverse[i]];
636 | }
637 | real = revReal;
638 | imag = revImag;
639 | }
640 |
641 | // lookup tables
642 |
643 | var sinlookup;// = [];
644 | var coslookup;// = [];
645 |
646 | function sin(i)
647 | {
648 | return sinlookup[i];
649 | }
650 |
651 | function cos(i)
652 | {
653 | return coslookup[i];
654 | }
655 |
656 | function buildTrigTables()
657 | {
658 | var N = timeSize;
659 | sinlookup = new Float32Array(N);
660 | coslookup = new Float32Array(N);
661 | for (var i = 0; i < N; i++)
662 | {
663 | sinlookup[i] = Math.sin(-Math.PI / i);
664 | coslookup[i] = Math.cos(-Math.PI / i);
665 | }
666 | }
667 |
668 | /////////
669 |
670 |
671 | /** The float value of 2*PI. Provided as a convenience for subclasses. */
672 | // protected static final float TWO_PI = (float) (2 * Math.PI);
673 | var length;
674 |
675 | // public WindowFunction()
676 | // {
677 | // }
678 |
679 | /**
680 | * Apply the window function to a sample buffer.
681 | *
682 | * @param samples a sample buffer
683 | */
684 | function apply(samples)
685 | {
686 | this.length = samples.length;
687 |
688 | for (var n = 0; n < samples.length; n ++)
689 | {
690 | samples[n] *= 1; //value(samples.length, n);
691 | }
692 | }
693 |
694 | /**
695 | protected float value(int length, int index)
696 | {
697 | return 1f;
698 | }
699 | */
700 |
701 | /**
702 | * Apply the window to a portion of this sample buffer,
703 | * given an offset from the beginning of the buffer
704 | * and the number of samples to be windowed.
705 | */
706 | function apply(samples, offset, l)
707 | {
708 | length = l;
709 |
710 | for(var n = offset; n < offset + length; ++n)
711 | {
712 | samples[n] *= value(length, n - offset);
713 | }
714 | }
715 |
716 | /**
717 | * Generates the curve of the window function.
718 | *
719 | * @param length the length of the window
720 | * @return the shape of the window function
721 | */
722 | // public float[] generateCurve(int length)
723 | // {
724 | // float[] samples = new float[length];
725 | // for (int n = 0; n < length; n++)
726 | // {
727 | // samples[n] = 1f * value(length, n);
728 | // }
729 | // return samples;
730 | // }
731 |
732 | // protected abstract float value(int length, int index);
733 |
734 |
735 |
736 | };
--------------------------------------------------------------------------------