├── .gitignore ├── LICENSE.txt ├── README.md ├── build.sh ├── compiler.jar ├── demo.html ├── externs.js └── jsfxr.js /.gitignore: -------------------------------------------------------------------------------- 1 | jsfxr.min.js 2 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | jsfxr 2 | ===== 3 | 4 | as3fxr (http://code.google.com/p/as3sfxr/) synth port to JavaScript created for js13kGames 5 | 6 | Licensed under Apache License 2.0 7 | 8 | Current version contains various performance/browser compatibility improvements by [@maettig](https://twitter.com/maettig) 9 | 10 | New minified size is 2517 bytes (Closure with Advanced Mode) thanks to improvements by [@chandlerprall](https://github.com/chandlerprall) and [@gheja](https://github.com/gheja). 11 | 12 | Pull requests for further improvements are welcome ;) 13 | 14 | Tested with FF 14, Chrome 21 and Opera 12 15 | 16 | Usage 17 | ===== 18 | 19 | 1. Create a sound with as3sfxr (http://www.superflashbros.net/as3sfxr/) 20 | 2. Copy settings string (Just use Ctrl+C on the as3fxr page) and save it as a JavaScript array 21 | * String looks something like this: "0,,0.1812,,0.1349,0.4524,,0.2365,,,,,,0.0819,,,,,1,,,,,0.5" 22 | * Should be passed as JavaScript array like this: [0,,0.1812,,0.1349,0.4524,,0.2365,,,,,,0.0819,,,,,1,,,,,0.5] 23 | 3. Play sound in JS using the following code: 24 | 25 | ```javascript 26 | // asfxr string gets passed into jsfxr as array 27 | var soundURL = jsfxr([0,,0.1812,,0.1349,0.4524,,0.2365,,,,,,0.0819,,,,,1,,,,,0.5]); 28 | var player = new Audio(); 29 | player.src = soundURL; 30 | player.play(); 31 | ``` 32 | 33 | Check out demo.html for some examples. Interactive demo is also available as [jsFiddle](http://jsfiddle.net/mneubrand/tsC8j/6/) 34 | -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # WARNING: the following assumes that the variable "x" is not used in jsfxr() _after_ the Closure Compiler 4 | 5 | # Compress JavaScript 6 | java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --externs externs.js --js jsfxr.js | \ 7 | tr -d '\n\r' | 8 | sed 's!"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\+/"!x!g' | \ 9 | sed 's!"data:audio/wav;base64,"!"data:audio/wav;base64,",x="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"!g' > jsfxr.min.js 10 | 11 | # Check file size 12 | wc -c jsfxr.min.js 13 | -------------------------------------------------------------------------------- /compiler.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mneubrand/jsfxr/b2bfe50fddc7e281e1c1944870071b2ccd2c0440/compiler.jar -------------------------------------------------------------------------------- /demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | jsfxr demo 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 43 | 44 | 45 | 46 |
47 |

jsfxr demo

48 |

as3fxr synth port to JavaScript created for js13kGames

49 |
50 |

51 | Play Explosion 52 | Play Powerup 53 | Play Jump 54 |

55 | 56 |

57 | 58 | 59 | Play Custom Sound 60 |

61 | 62 |

63 | Hosted as3sfxr by Tom Vian: http://www.superflashbros.net/as3sfxr/ 64 |

65 |
66 |
67 | 68 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /externs.js: -------------------------------------------------------------------------------- 1 | var x={}; 2 | -------------------------------------------------------------------------------- /jsfxr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * SfxrParams 3 | * 4 | * Copyright 2010 Thomas Vian 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | * @author Thomas Vian 19 | */ 20 | /** @constructor */ 21 | function SfxrParams() { 22 | //-------------------------------------------------------------------------- 23 | // 24 | // Settings String Methods 25 | // 26 | //-------------------------------------------------------------------------- 27 | 28 | /** 29 | * Parses a settings array into the parameters 30 | * @param array Array of the settings values, where elements 0 - 23 are 31 | * a: waveType 32 | * b: attackTime 33 | * c: sustainTime 34 | * d: sustainPunch 35 | * e: decayTime 36 | * f: startFrequency 37 | * g: minFrequency 38 | * h: slide 39 | * i: deltaSlide 40 | * j: vibratoDepth 41 | * k: vibratoSpeed 42 | * l: changeAmount 43 | * m: changeSpeed 44 | * n: squareDuty 45 | * o: dutySweep 46 | * p: repeatSpeed 47 | * q: phaserOffset 48 | * r: phaserSweep 49 | * s: lpFilterCutoff 50 | * t: lpFilterCutoffSweep 51 | * u: lpFilterResonance 52 | * v: hpFilterCutoff 53 | * w: hpFilterCutoffSweep 54 | * x: masterVolume 55 | * @return If the string successfully parsed 56 | */ 57 | this.setSettings = function(values) 58 | { 59 | for ( var i = 0; i < 24; i++ ) 60 | { 61 | this[String.fromCharCode( 97 + i )] = values[i] || 0; 62 | } 63 | 64 | // I moved this here from the reset(true) function 65 | if (this['c'] < .01) { 66 | this['c'] = .01; 67 | } 68 | 69 | var totalTime = this['b'] + this['c'] + this['e']; 70 | if (totalTime < .18) { 71 | var multiplier = .18 / totalTime; 72 | this['b'] *= multiplier; 73 | this['c'] *= multiplier; 74 | this['e'] *= multiplier; 75 | } 76 | } 77 | } 78 | 79 | /** 80 | * SfxrSynth 81 | * 82 | * Copyright 2010 Thomas Vian 83 | * 84 | * Licensed under the Apache License, Version 2.0 (the "License"); 85 | * you may not use this file except in compliance with the License. 86 | * You may obtain a copy of the License at 87 | * 88 | * http://www.apache.org/licenses/LICENSE-2.0 89 | * 90 | * Unless required by applicable law or agreed to in writing, software 91 | * distributed under the License is distributed on an "AS IS" BASIS, 92 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 93 | * See the License for the specific language governing permissions and 94 | * limitations under the License. 95 | * 96 | * @author Thomas Vian 97 | */ 98 | /** @constructor */ 99 | function SfxrSynth() { 100 | // All variables are kept alive through function closures 101 | 102 | //-------------------------------------------------------------------------- 103 | // 104 | // Sound Parameters 105 | // 106 | //-------------------------------------------------------------------------- 107 | 108 | this._params = new SfxrParams(); // Params instance 109 | 110 | //-------------------------------------------------------------------------- 111 | // 112 | // Synth Variables 113 | // 114 | //-------------------------------------------------------------------------- 115 | 116 | var _envelopeLength0, // Length of the attack stage 117 | _envelopeLength1, // Length of the sustain stage 118 | _envelopeLength2, // Length of the decay stage 119 | 120 | _period, // Period of the wave 121 | _maxPeriod, // Maximum period before sound stops (from minFrequency) 122 | 123 | _slide, // Note slide 124 | _deltaSlide, // Change in slide 125 | 126 | _changeAmount, // Amount to change the note by 127 | _changeTime, // Counter for the note change 128 | _changeLimit, // Once the time reaches this limit, the note changes 129 | 130 | _squareDuty, // Offset of center switching point in the square wave 131 | _dutySweep; // Amount to change the duty by 132 | 133 | //-------------------------------------------------------------------------- 134 | // 135 | // Synth Methods 136 | // 137 | //-------------------------------------------------------------------------- 138 | 139 | /** 140 | * Resets the runing variables from the params 141 | * Used once at the start (total reset) and for the repeat effect (partial reset) 142 | */ 143 | this.reset = function() { 144 | // Shorter reference 145 | var p = this._params; 146 | 147 | _period = 100 / (p['f'] * p['f'] + .001); 148 | _maxPeriod = 100 / (p['g'] * p['g'] + .001); 149 | 150 | _slide = 1 - p['h'] * p['h'] * p['h'] * .01; 151 | _deltaSlide = -p['i'] * p['i'] * p['i'] * .000001; 152 | 153 | if (!p['a']) { 154 | _squareDuty = .5 - p['n'] / 2; 155 | _dutySweep = -p['o'] * .00005; 156 | } 157 | 158 | _changeAmount = 1 + p['l'] * p['l'] * (p['l'] > 0 ? -.9 : 10); 159 | _changeTime = 0; 160 | _changeLimit = p['m'] == 1 ? 0 : (1 - p['m']) * (1 - p['m']) * 20000 + 32; 161 | } 162 | 163 | // I split the reset() function into two functions for better readability 164 | this.totalReset = function() { 165 | this.reset(); 166 | 167 | // Shorter reference 168 | var p = this._params; 169 | 170 | // Calculating the length is all that remained here, everything else moved somewhere 171 | _envelopeLength0 = p['b'] * p['b'] * 100000; 172 | _envelopeLength1 = p['c'] * p['c'] * 100000; 173 | _envelopeLength2 = p['e'] * p['e'] * 100000 + 12; 174 | // Full length of the volume envelop (and therefore sound) 175 | // Make sure the length can be divided by 3 so we will not need the padding "==" after base64 encode 176 | return ((_envelopeLength0 + _envelopeLength1 + _envelopeLength2) / 3 | 0) * 3; 177 | } 178 | 179 | /** 180 | * Writes the wave to the supplied buffer ByteArray 181 | * @param buffer A ByteArray to write the wave to 182 | * @return If the wave is finished 183 | */ 184 | this.synthWave = function(buffer, length) { 185 | // Shorter reference 186 | var p = this._params; 187 | 188 | // If the filters are active 189 | var _filters = p['s'] != 1 || p['v'], 190 | // Cutoff multiplier which adjusts the amount the wave position can move 191 | _hpFilterCutoff = p['v'] * p['v'] * .1, 192 | // Speed of the high-pass cutoff multiplier 193 | _hpFilterDeltaCutoff = 1 + p['w'] * .0003, 194 | // Cutoff multiplier which adjusts the amount the wave position can move 195 | _lpFilterCutoff = p['s'] * p['s'] * p['s'] * .1, 196 | // Speed of the low-pass cutoff multiplier 197 | _lpFilterDeltaCutoff = 1 + p['t'] * .0001, 198 | // If the low pass filter is active 199 | _lpFilterOn = p['s'] != 1, 200 | // masterVolume * masterVolume (for quick calculations) 201 | _masterVolume = p['x'] * p['x'], 202 | // Minimum frequency before stopping 203 | _minFreqency = p['g'], 204 | // If the phaser is active 205 | _phaser = p['q'] || p['r'], 206 | // Change in phase offset 207 | _phaserDeltaOffset = p['r'] * p['r'] * p['r'] * .2, 208 | // Phase offset for phaser effect 209 | _phaserOffset = p['q'] * p['q'] * (p['q'] < 0 ? -1020 : 1020), 210 | // Once the time reaches this limit, some of the iables are reset 211 | _repeatLimit = p['p'] ? ((1 - p['p']) * (1 - p['p']) * 20000 | 0) + 32 : 0, 212 | // The punch factor (louder at begining of sustain) 213 | _sustainPunch = p['d'], 214 | // Amount to change the period of the wave by at the peak of the vibrato wave 215 | _vibratoAmplitude = p['j'] / 2, 216 | // Speed at which the vibrato phase moves 217 | _vibratoSpeed = p['k'] * p['k'] * .01, 218 | // The type of wave to generate 219 | _waveType = p['a']; 220 | 221 | var _envelopeLength = _envelopeLength0, // Length of the current envelope stage 222 | _envelopeOverLength0 = 1 / _envelopeLength0, // (for quick calculations) 223 | _envelopeOverLength1 = 1 / _envelopeLength1, // (for quick calculations) 224 | _envelopeOverLength2 = 1 / _envelopeLength2; // (for quick calculations) 225 | 226 | // Damping muliplier which restricts how fast the wave position can move 227 | var _lpFilterDamping = 5 / (1 + p['u'] * p['u'] * 20) * (.01 + _lpFilterCutoff); 228 | if (_lpFilterDamping > .8) { 229 | _lpFilterDamping = .8; 230 | } 231 | _lpFilterDamping = 1 - _lpFilterDamping; 232 | 233 | var _finished = false, // If the sound has finished 234 | _envelopeStage = 0, // Current stage of the envelope (attack, sustain, decay, end) 235 | _envelopeTime = 0, // Current time through current enelope stage 236 | _envelopeVolume = 0, // Current volume of the envelope 237 | _hpFilterPos = 0, // Adjusted wave position after high-pass filter 238 | _lpFilterDeltaPos = 0, // Change in low-pass wave position, as allowed by the cutoff and damping 239 | _lpFilterOldPos, // Previous low-pass wave position 240 | _lpFilterPos = 0, // Adjusted wave position after low-pass filter 241 | _periodTemp, // Period modified by vibrato 242 | _phase = 0, // Phase through the wave 243 | _phaserInt, // Integer phaser offset, for bit maths 244 | _phaserPos = 0, // Position through the phaser buffer 245 | _pos, // Phase expresed as a Number from 0-1, used for fast sin approx 246 | _repeatTime = 0, // Counter for the repeats 247 | _sample, // Sub-sample calculated 8 times per actual sample, averaged out to get the super sample 248 | _superSample, // Actual sample writen to the wave 249 | _vibratoPhase = 0; // Phase through the vibrato sine wave 250 | 251 | // Buffer of wave values used to create the out of phase second wave 252 | var _phaserBuffer = new Array(1024), 253 | // Buffer of random values used to generate noise 254 | _noiseBuffer = new Array(32); 255 | for (var i = _phaserBuffer.length; i--; ) { 256 | _phaserBuffer[i] = 0; 257 | } 258 | for (var i = _noiseBuffer.length; i--; ) { 259 | _noiseBuffer[i] = Math.random() * 2 - 1; 260 | } 261 | 262 | for (var i = 0; i < length; i++) { 263 | if (_finished) { 264 | return i; 265 | } 266 | 267 | // Repeats every _repeatLimit times, partially resetting the sound parameters 268 | if (_repeatLimit) { 269 | if (++_repeatTime >= _repeatLimit) { 270 | _repeatTime = 0; 271 | this.reset(); 272 | } 273 | } 274 | 275 | // If _changeLimit is reached, shifts the pitch 276 | if (_changeLimit) { 277 | if (++_changeTime >= _changeLimit) { 278 | _changeLimit = 0; 279 | _period *= _changeAmount; 280 | } 281 | } 282 | 283 | // Acccelerate and apply slide 284 | _slide += _deltaSlide; 285 | _period *= _slide; 286 | 287 | // Checks for frequency getting too low, and stops the sound if a minFrequency was set 288 | if (_period > _maxPeriod) { 289 | _period = _maxPeriod; 290 | if (_minFreqency > 0) { 291 | _finished = true; 292 | } 293 | } 294 | 295 | _periodTemp = _period; 296 | 297 | // Applies the vibrato effect 298 | if (_vibratoAmplitude > 0) { 299 | _vibratoPhase += _vibratoSpeed; 300 | _periodTemp *= 1 + Math.sin(_vibratoPhase) * _vibratoAmplitude; 301 | } 302 | 303 | _periodTemp |= 0; 304 | if (_periodTemp < 8) { 305 | _periodTemp = 8; 306 | } 307 | 308 | // Sweeps the square duty 309 | if (!_waveType) { 310 | _squareDuty += _dutySweep; 311 | if (_squareDuty < 0) { 312 | _squareDuty = 0; 313 | } else if (_squareDuty > .5) { 314 | _squareDuty = .5; 315 | } 316 | } 317 | 318 | // Moves through the different stages of the volume envelope 319 | if (++_envelopeTime > _envelopeLength) { 320 | _envelopeTime = 0; 321 | 322 | switch (++_envelopeStage) { 323 | case 1: 324 | _envelopeLength = _envelopeLength1; 325 | break; 326 | case 2: 327 | _envelopeLength = _envelopeLength2; 328 | } 329 | } 330 | 331 | // Sets the volume based on the position in the envelope 332 | switch (_envelopeStage) { 333 | case 0: 334 | _envelopeVolume = _envelopeTime * _envelopeOverLength0; 335 | break; 336 | case 1: 337 | _envelopeVolume = 1 + (1 - _envelopeTime * _envelopeOverLength1) * 2 * _sustainPunch; 338 | break; 339 | case 2: 340 | _envelopeVolume = 1 - _envelopeTime * _envelopeOverLength2; 341 | break; 342 | case 3: 343 | _envelopeVolume = 0; 344 | _finished = true; 345 | } 346 | 347 | // Moves the phaser offset 348 | if (_phaser) { 349 | _phaserOffset += _phaserDeltaOffset; 350 | _phaserInt = _phaserOffset | 0; 351 | if (_phaserInt < 0) { 352 | _phaserInt = -_phaserInt; 353 | } else if (_phaserInt > 1023) { 354 | _phaserInt = 1023; 355 | } 356 | } 357 | 358 | // Moves the high-pass filter cutoff 359 | if (_filters && _hpFilterDeltaCutoff) { 360 | _hpFilterCutoff *= _hpFilterDeltaCutoff; 361 | if (_hpFilterCutoff < .00001) { 362 | _hpFilterCutoff = .00001; 363 | } else if (_hpFilterCutoff > .1) { 364 | _hpFilterCutoff = .1; 365 | } 366 | } 367 | 368 | _superSample = 0; 369 | for (var j = 8; j--; ) { 370 | // Cycles through the period 371 | _phase++; 372 | if (_phase >= _periodTemp) { 373 | _phase %= _periodTemp; 374 | 375 | // Generates new random noise for this period 376 | if (_waveType == 3) { 377 | for (var n = _noiseBuffer.length; n--; ) { 378 | _noiseBuffer[n] = Math.random() * 2 - 1; 379 | } 380 | } 381 | } 382 | 383 | // Gets the sample from the oscillator 384 | switch (_waveType) { 385 | case 0: // Square wave 386 | _sample = ((_phase / _periodTemp) < _squareDuty) ? .5 : -.5; 387 | break; 388 | case 1: // Saw wave 389 | _sample = 1 - _phase / _periodTemp * 2; 390 | break; 391 | case 2: // Sine wave (fast and accurate approx) 392 | _pos = _phase / _periodTemp; 393 | _pos = (_pos > .5 ? _pos - 1 : _pos) * 6.28318531; 394 | _sample = 1.27323954 * _pos + .405284735 * _pos * _pos * (_pos < 0 ? 1 : -1); 395 | _sample = .225 * ((_sample < 0 ? -1 : 1) * _sample * _sample - _sample) + _sample; 396 | break; 397 | case 3: // Noise 398 | _sample = _noiseBuffer[Math.abs(_phase * 32 / _periodTemp | 0)]; 399 | } 400 | 401 | // Applies the low and high pass filters 402 | if (_filters) { 403 | _lpFilterOldPos = _lpFilterPos; 404 | _lpFilterCutoff *= _lpFilterDeltaCutoff; 405 | if (_lpFilterCutoff < 0) { 406 | _lpFilterCutoff = 0; 407 | } else if (_lpFilterCutoff > .1) { 408 | _lpFilterCutoff = .1; 409 | } 410 | 411 | if (_lpFilterOn) { 412 | _lpFilterDeltaPos += (_sample - _lpFilterPos) * _lpFilterCutoff; 413 | _lpFilterDeltaPos *= _lpFilterDamping; 414 | } else { 415 | _lpFilterPos = _sample; 416 | _lpFilterDeltaPos = 0; 417 | } 418 | 419 | _lpFilterPos += _lpFilterDeltaPos; 420 | 421 | _hpFilterPos += _lpFilterPos - _lpFilterOldPos; 422 | _hpFilterPos *= 1 - _hpFilterCutoff; 423 | _sample = _hpFilterPos; 424 | } 425 | 426 | // Applies the phaser effect 427 | if (_phaser) { 428 | _phaserBuffer[_phaserPos % 1024] = _sample; 429 | _sample += _phaserBuffer[(_phaserPos - _phaserInt + 1024) % 1024]; 430 | _phaserPos++; 431 | } 432 | 433 | _superSample += _sample; 434 | } 435 | 436 | // Averages out the super samples and applies volumes 437 | _superSample *= .125 * _envelopeVolume * _masterVolume; 438 | 439 | // Clipping if too loud 440 | buffer[i] = _superSample >= 1 ? 32767 : _superSample <= -1 ? -32768 : _superSample * 32767 | 0; 441 | } 442 | 443 | return length; 444 | } 445 | } 446 | 447 | // Adapted from http://codebase.es/riffwave/ 448 | var synth = new SfxrSynth(); 449 | // Export for the Closure Compiler 450 | window['jsfxr'] = function(settings) { 451 | // Initialize SfxrParams 452 | synth._params.setSettings(settings); 453 | // Synthesize Wave 454 | var envelopeFullLength = synth.totalReset(); 455 | var data = new Uint8Array(((envelopeFullLength + 1) / 2 | 0) * 4 + 44); 456 | var used = synth.synthWave(new Uint16Array(data.buffer, 44), envelopeFullLength) * 2; 457 | var dv = new Uint32Array(data.buffer, 0, 44); 458 | // Initialize header 459 | dv[0] = 0x46464952; // "RIFF" 460 | dv[1] = used + 36; // put total size here 461 | dv[2] = 0x45564157; // "WAVE" 462 | dv[3] = 0x20746D66; // "fmt " 463 | dv[4] = 0x00000010; // size of the following 464 | dv[5] = 0x00010001; // Mono: 1 channel, PCM format 465 | dv[6] = 0x0000AC44; // 44,100 samples per second 466 | dv[7] = 0x00015888; // byte rate: two bytes per sample 467 | dv[8] = 0x00100002; // 16 bits per sample, aligned on every two bytes 468 | dv[9] = 0x61746164; // "data" 469 | dv[10] = used; // put number of samples here 470 | 471 | // Base64 encoding written by me, @maettig 472 | used += 44; 473 | var i = 0, 474 | base64Characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/', 475 | output = 'data:audio/wav;base64,'; 476 | for (; i < used; i += 3) 477 | { 478 | var a = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; 479 | output += base64Characters[a >> 18] + base64Characters[a >> 12 & 63] + base64Characters[a >> 6 & 63] + base64Characters[a & 63]; 480 | } 481 | return output; 482 | } 483 | --------------------------------------------------------------------------------