├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitattributes
├── .github
├── CONTRIBUTING.md
├── ISSUE_TEMPLATE.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ ├── ci-cd.yml
│ ├── commitlint.yml
│ └── signature-assistant.yml
├── .gitignore
├── .husky
├── .gitattributes
└── commit-msg
├── .npmignore
├── .nvmrc
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── TRADEMARK.txt
├── commitlint.config.js
├── package-lock.json
├── package.json
├── release.config.js
├── renovate.json5
├── sound-files
└── drums
│ ├── BassDrum(1b)_22k.wav
│ ├── Bongo_22k.wav
│ ├── Cabasa(1)_22k.wav
│ ├── Clap(1)_22k.wav
│ ├── Claves(1)_22k.wav
│ ├── Conga(1)_22k.wav
│ ├── Cowbell(3)_22k.wav
│ ├── Crash(2)_22k.wav
│ ├── Cuica(2)_22k.wav
│ ├── GuiroLong(1)_22k.wav
│ ├── GuiroShort(1)_22k.wav
│ ├── HiHatClosed(1)_22k.wav
│ ├── HiHatOpen(2)_22k.wav
│ ├── HiHatPedal(1)_22k.wav
│ ├── Maracas(1)_22k.wav
│ ├── SideStick(1)_22k.wav
│ ├── SnareDrum(1)_22k.wav
│ ├── Tambourine(3)_22k.wav
│ ├── Tom(1)_22k.wav
│ ├── Triangle(1)_22k.wav
│ ├── Vibraslap(1)_22k.wav
│ └── WoodBlock(1)_22k.wav
├── src
├── .eslintrc.js
├── ADPCMSoundDecoder.js
├── ArrayBufferStream.js
├── AudioEngine.js
├── Loudness.js
├── SoundBank.js
├── SoundPlayer.js
├── StartAudioContext.js
├── effects
│ ├── Effect.js
│ ├── EffectChain.js
│ ├── PanEffect.js
│ ├── PitchEffect.js
│ └── VolumeEffect.js
├── index.js
├── log.js
└── uid.js
├── test
├── AudioEngine.js
├── SoundPlayer.js
├── __mocks__
│ ├── AudioContext.js
│ ├── AudioEngine.js
│ ├── AudioNode.js
│ ├── AudioParam.js
│ └── AudioTarget.js
└── effects
│ └── EffectShape.js
└── webpack.config.js
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | end_of_line = lf
5 | insert_final_newline = true
6 | charset = utf-8
7 | indent_size = 4
8 | trim_trailing_whitespace = true
9 |
10 | [*.{js,html}]
11 | indent_style = space
12 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | node_modules/*
2 | dist.js
3 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['scratch', 'scratch/node']
3 | };
4 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Set the default behavior, in case people don't have core.autocrlf set.
2 | * text=auto
3 |
4 | # Explicitly specify line endings for as many files as possible.
5 | # People who (for example) rsync between Windows and Linux need this.
6 |
7 | # File types which we know are binary
8 | *.wav binary
9 |
10 | # Prefer LF for most file types
11 | *.js text eol=lf
12 | *.js.map text eol=lf
13 | *.json text eol=lf
14 | *.json5 text eol=lf
15 | *.md text eol=lf
16 | *.yml text eol=lf
17 | *.txt text eol=lf
18 |
19 | # Prefer LF for these files
20 | .editorconfig text eol=lf
21 | .eslintignore text eol=lf
22 | .eslintrc text eol=lf
23 | .gitattributes text eol=lf
24 | .gitignore text eol=lf
25 | .npmignore text eol=lf
26 | LICENSE text eol=lf
27 |
28 | # Use CRLF for Windows-specific file types
29 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing
2 | The development of Scratch is an ongoing process, and we love to have people in the Scratch and open source communities help us along the way.
3 |
4 | ### Ways to Help
5 |
6 | * **Documenting bugs**
7 | * If you've identified a bug in Scratch you should first check to see if it's been filed as an issue, if not you can file one. Make sure you follow the issue template.
8 | * It's important that we can consistently reproduce issues. When writing an issue, be sure to follow our [reproduction step guidelines](https://github.com/LLK/scratch-gui/wiki/Writing-good-repro-steps).
9 | * Some issues are marked "Needs Repro". Adding a comment with good reproduction steps to those issues is a great way to help.
10 | * If you don't have an issue in mind already, you can look through the [Bugs & Glitches forum.](https://scratch.mit.edu/discuss/3/) Look for users reporting problems, reproduce the problem yourself, and file new issues following our guidelines.
11 |
12 | * **Fixing bugs**
13 | * You can request to fix a bug in a comment on the issue if you at mention the repo coordinator, who for this repo is @ericrosenbaum.
14 | * If the issue is marked "Help Wanted" you can go ahead and start working on it!
15 | * **We will only accept Pull Requests for bugs that have an issue filed that has a priority label**
16 | * If you're interested in fixing a bug with no issue, file the issue first and wait for it to have a priority added to it.
17 |
18 | * We are not looking for Pull Requests ("PR") for every issue and may deny a PR if it doesn't fit our criteria.
19 | * We are far more likely to accept a PR if it is for an issue marked with Help Wanted.
20 | * We will not accept PRs for issues marked with "Needs Discussion" or "Needs Design."
21 | * Wait until the Repo Coordinator assigns the issue to you before you begin work or submit a PR.
22 |
23 | ### Learning Git and Github
24 |
25 | If you want to work on fixing issues, you should be familiar with Git and Github.
26 |
27 | * [Learn Git branching](https://learngitbranching.js.org/) includes an introduction to basic git commands and useful branching features.
28 | * Here's a general introduction to [contributing to an open source project](https://egghead.io/courses/how-to-contribute-to-an-open-source-project-on-github).
29 |
30 | **Important:** we follow the [Github Flow process](https://guides.github.com/introduction/flow/) as our development process.
31 |
32 | ### How to Fix Bugs
33 | 1. Identify which Github issue you are working on. Leave a comment on the issue to let us (and other contributors) know you're working on it.
34 | 2. Make sure you have a fork of this repo (see [Github's forking a repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) for details)
35 | 3. Switch to the `develop` branch, and pull down the latest changes from upstream
36 | 4. Run the code, and reproduce the problem
37 | 5. Create your branch from the `develop` branch
38 | 6. Make code changes to fix the problem
39 | 7. Run `npm test` to make sure that your changes pass our tests
40 | 8. Commit your changes
41 | 9. Push your branch to your fork
42 | 10. Create your pull request
43 | 1. Make sure to follow the template in the PR description
44 | 1. Remember to check the “[Allow edits from maintainers](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork)” box
45 |
46 | When submitting pull requests keep in mind:
47 | * please be patient -- it can take a while to find time to review them
48 | * try to change the least amount of code necessary to fix the bug
49 | * the code can't be radically changed without significant coordination with the Scratch Team, so these types of changes should be avoided
50 | * if you find yourself changing a substantial amount of code or considering radical changes, please ask for clarification -- we may have envisioned a different approach, or underestimated the amount of effort
51 |
52 | ### Suggestions
53 | 
54 |
55 | Please note: **_we are unlikely to accept PRs with new features that haven't been thought through and discussed as a group_**.
56 |
57 | Why? Because we have a strong belief in the value of keeping things simple for new users. It's been said that the Scratch Team spends about one hour of design discussion for every pixel in Scratch. To learn more about our design philosophy, see [the Scratch Developers page](https://scratch.mit.edu/developers), or [this paper](http://web.media.mit.edu/~mres/papers/Scratch-CACM-final.pdf).
58 |
59 | We welcome suggestions! If you want to suggest a feature, please post in our [suggestions forum](https://scratch.mit.edu/discuss/1/). Your suggestion will be helped if you include a mockup design; this can be simple, even hand-drawn.
60 |
61 | ### Other resources
62 | Beyond this repo, there are also some other resources that you might want to take a look at:
63 | * [Community Guidelines](https://github.com/LLK/scratch-www/wiki/Community-Guidelines) (we find it important to maintain a constructive and welcoming community, just like on Scratch)
64 | * [Open Source forum](https://scratch.mit.edu/discuss/49/) on Scratch
65 | * [Suggestions forum](https://scratch.mit.edu/discuss/1/) on Scratch
66 | * [Bugs & Glitches forum](https://scratch.mit.edu/discuss/3/) on Scratch
67 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Expected behavior
2 |
3 | _Please describe what should happen_
4 |
5 | ### Actual behavior
6 |
7 | _Describe what actually happens_
8 |
9 | ### Steps to reproduce
10 |
11 | _Explain what someone needs to do in order to see what's described in *Actual behavior* above_
12 |
13 | ### Operating system and browser
14 |
15 | _e.g. Mac OS 10.11.6 Safari 10.0_
16 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Proposed changes
2 |
3 | _Describe what this Pull Request does_
4 |
5 | ### Reason for changes
6 |
7 | _Explain why these changes should be made. Please include an issue # if applicable._
8 |
--------------------------------------------------------------------------------
/.github/workflows/ci-cd.yml:
--------------------------------------------------------------------------------
1 | #
2 | name: CI/CD
3 |
4 | on:
5 | workflow_dispatch: # Allows you to run this workflow manually from the Actions tab
6 | push: # Runs whenever a commit is pushed to the repository
7 |
8 | concurrency:
9 | group: "${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}"
10 | cancel-in-progress: true
11 |
12 | permissions:
13 | contents: write # publish a GitHub release
14 | pages: write # deploy to GitHub Pages
15 | issues: write # comment on released issues
16 | pull-requests: write # comment on released pull requests
17 |
18 | jobs:
19 | ci-cd:
20 | runs-on: ubuntu-latest
21 | env:
22 | TRIGGER_DEPLOY: ${{ startsWith(github.ref, 'refs/heads/master') || startsWith(github.ref, 'refs/heads/hotfix') || startsWith(github.ref, 'refs/heads/develop') || startsWith(github.ref, 'refs/heads/beta') }}
23 | steps:
24 | - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4
25 | - uses: wagoid/commitlint-github-action@5ce82f5d814d4010519d15f0552aec4f17a1e1fe # v5
26 | if: github.event_name == 'pull_request'
27 | - uses: actions/setup-node@1a4442cacd436585916779262731d5b162bc6ec7 # v3
28 | with:
29 | cache: "npm"
30 | node-version-file: ".nvmrc"
31 |
32 | - name: Info
33 | run: |
34 | cat <
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # scratch-audio
2 | #### Scratch audio engine is for playing sounds, instruments and audio effects in Scratch 3.0 projects
3 |
4 | [](https://greenkeeper.io/)
5 |
6 | #### Please note this project is at an early stage and we are not ready for pull requests
7 |
8 | [](https://circleci.com/gh/LLK/scratch-audio?branch=develop)
9 |
10 | ## Installation
11 | This requires you to have Git and Node.js installed.
12 |
13 | In your own node environment/application:
14 | ```bash
15 | npm install https://github.com/scratchfoundation/scratch-audio.git
16 | ```
17 | If you want to edit/play yourself:
18 | ```bash
19 | git clone git@github.com:LLK/scratch-audio.git
20 | cd scratch-audio
21 | npm install
22 | ```
23 |
24 | ## Testing
25 | ```bash
26 | npm test
27 | ```
28 |
29 | ## Donate
30 | We provide [Scratch](https://scratch.mit.edu) free of charge, and want to keep it that way! Please consider making a [donation](https://secure.donationpay.org/scratchfoundation/) to support our continued engineering, design, community, and resource development efforts. Donations of any size are appreciated. Thank you!
31 |
32 | ## Committing
33 |
34 | This project uses [semantic release](https://github.com/semantic-release/semantic-release) to ensure version bumps
35 | follow semver so that projects depending on it don't break unexpectedly.
36 |
37 | In order to automatically determine version updates, semantic release expects commit messages to follow the
38 | [conventional-changelog](https://github.com/bcoe/conventional-changelog-standard/blob/master/convention.md)
39 | specification.
40 |
41 | You can use the [commitizen CLI](https://github.com/commitizen/cz-cli) to make commits formatted in this way:
42 |
43 | ```bash
44 | npm install -g commitizen@latest cz-conventional-changelog@latest
45 | ```
46 |
47 | Now you're ready to make commits using `git cz`.
48 |
--------------------------------------------------------------------------------
/TRADEMARK.txt:
--------------------------------------------------------------------------------
1 | The Scratch trademarks, including the Scratch name, logo, the Scratch Cat, Gobo, Pico, Nano, Tera and Giga graphics (the "Marks"), are property of the Massachusetts Institute of Technology (MIT). Marks may not be used to endorse or promote products derived from this software without specific prior written permission.
2 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: ['@commitlint/config-conventional'],
3 | ignores: [message => message.startsWith('chore(release):')]
4 | };
5 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "scratch-audio",
3 | "version": "2.0.155",
4 | "description": "audio engine for scratch 3.0",
5 | "main": "dist.js",
6 | "browser": "./src/index.js",
7 | "scripts": {
8 | "build": "webpack --bail",
9 | "lint": "eslint .",
10 | "prepare": "husky install",
11 | "tap": "tap test/effects/*.js test/*.js",
12 | "test": "npm run lint && npm run tap && npm run build",
13 | "watch": "webpack --watch"
14 | },
15 | "repository": {
16 | "type": "git",
17 | "url": "git+https://github.com/scratchfoundation/scratch-audio.git"
18 | },
19 | "author": "Massachusetts Institute of Technology",
20 | "license": "AGPL-3.0-only",
21 | "bugs": {
22 | "url": "https://github.com/scratchfoundation/scratch-audio/issues"
23 | },
24 | "homepage": "https://github.com/scratchfoundation/scratch-audio#readme",
25 | "dependencies": {
26 | "audio-context": "^1.0.1",
27 | "minilog": "^3.0.1",
28 | "startaudiocontext": "^1.2.1"
29 | },
30 | "devDependencies": {
31 | "@commitlint/cli": "18.6.1",
32 | "@commitlint/config-conventional": "18.6.3",
33 | "babel-core": "6.26.3",
34 | "babel-eslint": "10.1.0",
35 | "babel-loader": "7.1.5",
36 | "babel-preset-env": "1.7.0",
37 | "eslint": "8.57.1",
38 | "eslint-config-scratch": "9.0.9",
39 | "husky": "8.0.3",
40 | "json": "9.0.6",
41 | "scratch-semantic-release-config": "3.0.0",
42 | "semantic-release": "19.0.5",
43 | "tap": "12.7.0",
44 | "web-audio-test-api": "0.5.2",
45 | "webpack": "4.47.0",
46 | "webpack-cli": "3.3.12"
47 | },
48 | "config": {
49 | "commitizen": {
50 | "path": "cz-conventional-changelog"
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/release.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | extends: 'scratch-semantic-release-config',
3 | branches: [
4 | {
5 | name: 'develop'
6 | // default channel
7 | },
8 | {
9 | name: 'hotfix/*',
10 | channel: 'hotfix',
11 | prerelease: 'hotfix'
12 | }
13 | ]
14 | };
15 |
--------------------------------------------------------------------------------
/renovate.json5:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json",
3 |
4 | "extends": [
5 | "github>scratchfoundation/scratch-renovate-config:js-lib-bundled"
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/sound-files/drums/BassDrum(1b)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/BassDrum(1b)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Bongo_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Bongo_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Cabasa(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Cabasa(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Clap(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Clap(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Claves(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Claves(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Conga(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Conga(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Cowbell(3)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Cowbell(3)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Crash(2)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Crash(2)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Cuica(2)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Cuica(2)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/GuiroLong(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/GuiroLong(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/GuiroShort(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/GuiroShort(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/HiHatClosed(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/HiHatClosed(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/HiHatOpen(2)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/HiHatOpen(2)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/HiHatPedal(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/HiHatPedal(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Maracas(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Maracas(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/SideStick(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/SideStick(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/SnareDrum(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/SnareDrum(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Tambourine(3)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Tambourine(3)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Tom(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Tom(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Triangle(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Triangle(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/Vibraslap(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/Vibraslap(1)_22k.wav
--------------------------------------------------------------------------------
/sound-files/drums/WoodBlock(1)_22k.wav:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/scratchfoundation/scratch-audio/9161bd036f8abe9f550d9cbf88f653a6d6289e73/sound-files/drums/WoodBlock(1)_22k.wav
--------------------------------------------------------------------------------
/src/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | extends: ['scratch', 'scratch/es6'],
4 | env: {browser: true}
5 | };
6 |
--------------------------------------------------------------------------------
/src/ADPCMSoundDecoder.js:
--------------------------------------------------------------------------------
1 | const ArrayBufferStream = require('./ArrayBufferStream');
2 | const log = require('./log');
3 |
4 | /**
5 | * Data used by the decompression algorithm
6 | * @type {Array}
7 | */
8 | const STEP_TABLE = [
9 | 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
10 | 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230,
11 | 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963,
12 | 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327,
13 | 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487,
14 | 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
15 | ];
16 |
17 | /**
18 | * Data used by the decompression algorithm
19 | * @type {Array}
20 | */
21 | const INDEX_TABLE = [
22 | -1, -1, -1, -1, 2, 4, 6, 8,
23 | -1, -1, -1, -1, 2, 4, 6, 8
24 | ];
25 |
26 | let _deltaTable = null;
27 |
28 | /**
29 | * Build a table of deltas from the 89 possible steps and 16 codes.
30 | * @return {Array} computed delta values
31 | */
32 | const deltaTable = function () {
33 | if (_deltaTable === null) {
34 | const NUM_STEPS = STEP_TABLE.length;
35 | const NUM_INDICES = INDEX_TABLE.length;
36 | _deltaTable = new Array(NUM_STEPS * NUM_INDICES).fill(0);
37 | let i = 0;
38 |
39 | for (let index = 0; index < NUM_STEPS; index++) {
40 | for (let code = 0; code < NUM_INDICES; code++) {
41 | const step = STEP_TABLE[index];
42 |
43 | let delta = 0;
44 | if (code & 4) delta += step;
45 | if (code & 2) delta += step >> 1;
46 | if (code & 1) delta += step >> 2;
47 | delta += step >> 3;
48 | _deltaTable[i++] = (code & 8) ? -delta : delta;
49 | }
50 | }
51 | }
52 |
53 | return _deltaTable;
54 | };
55 |
56 | /**
57 | * Decode wav audio files that have been compressed with the ADPCM format.
58 | * This is necessary because, while web browsers have native decoders for many audio
59 | * formats, ADPCM is a non-standard format used by Scratch since its early days.
60 | * This decoder is based on code from Scratch-Flash:
61 | * https://github.com/LLK/scratch-flash/blob/master/src/sound/WAVFile.as
62 | */
63 | class ADPCMSoundDecoder {
64 | /**
65 | * @param {AudioContext} audioContext - a webAudio context
66 | * @constructor
67 | */
68 | constructor (audioContext) {
69 | this.audioContext = audioContext;
70 | }
71 |
72 | /**
73 | * Data used by the decompression algorithm
74 | * @type {Array}
75 | */
76 | static get STEP_TABLE () {
77 | return STEP_TABLE;
78 | }
79 |
80 | /**
81 | * Data used by the decompression algorithm
82 | * @type {Array}
83 | */
84 | static get INDEX_TABLE () {
85 | return INDEX_TABLE;
86 | }
87 |
88 | /**
89 | * Decode an ADPCM sound stored in an ArrayBuffer and return a promise
90 | * with the decoded audio buffer.
91 | * @param {ArrayBuffer} audioData - containing ADPCM encoded wav audio
92 | * @return {Promise.} the decoded audio buffer
93 | */
94 | decode (audioData) {
95 |
96 | return new Promise((resolve, reject) => {
97 | const stream = new ArrayBufferStream(audioData);
98 |
99 | const riffStr = stream.readUint8String(4);
100 | if (riffStr !== 'RIFF') {
101 | log.warn('incorrect adpcm wav header');
102 | reject(new Error('incorrect adpcm wav header'));
103 | }
104 |
105 | const lengthInHeader = stream.readInt32();
106 | if ((lengthInHeader + 8) !== audioData.byteLength) {
107 | log.warn(`adpcm wav length in header: ${lengthInHeader} is incorrect`);
108 | }
109 |
110 | const wavStr = stream.readUint8String(4);
111 | if (wavStr !== 'WAVE') {
112 | log.warn('incorrect adpcm wav header');
113 | reject(new Error('incorrect adpcm wav header'));
114 | }
115 |
116 | const formatChunk = this.extractChunk('fmt ', stream);
117 | this.encoding = formatChunk.readUint16();
118 | this.channels = formatChunk.readUint16();
119 | this.samplesPerSecond = formatChunk.readUint32();
120 | this.bytesPerSecond = formatChunk.readUint32();
121 | this.blockAlignment = formatChunk.readUint16();
122 | this.bitsPerSample = formatChunk.readUint16();
123 | formatChunk.position += 2; // skip extra header byte count
124 | this.samplesPerBlock = formatChunk.readUint16();
125 | this.adpcmBlockSize = ((this.samplesPerBlock - 1) / 2) + 4; // block size in bytes
126 |
127 | const compressedData = this.extractChunk('data', stream);
128 | const sampleCount = this.numberOfSamples(compressedData, this.adpcmBlockSize);
129 |
130 | const buffer = this.audioContext.createBuffer(1, sampleCount, this.samplesPerSecond);
131 | this.imaDecompress(compressedData, this.adpcmBlockSize, buffer.getChannelData(0));
132 |
133 | resolve(buffer);
134 | });
135 | }
136 |
137 | /**
138 | * Extract a chunk of audio data from the stream, consisting of a set of audio data bytes
139 | * @param {string} chunkType - the type of chunk to extract. 'data' or 'fmt' (format)
140 | * @param {ArrayBufferStream} stream - an stream containing the audio data
141 | * @return {ArrayBufferStream} a stream containing the desired chunk
142 | */
143 | extractChunk (chunkType, stream) {
144 | stream.position = 12;
145 | while (stream.position < (stream.getLength() - 8)) {
146 | const typeStr = stream.readUint8String(4);
147 | const chunkSize = stream.readInt32();
148 | if (typeStr === chunkType) {
149 | const chunk = stream.extract(chunkSize);
150 | return chunk;
151 | }
152 | stream.position += chunkSize;
153 |
154 | }
155 | }
156 |
157 | /**
158 | * Count the exact number of samples in the compressed data.
159 | * @param {ArrayBufferStream} compressedData - the compressed data
160 | * @param {number} blockSize - size of each block in the data in bytes
161 | * @return {number} number of samples in the compressed data
162 | */
163 | numberOfSamples (compressedData, blockSize) {
164 | if (!compressedData) return 0;
165 |
166 | compressedData.position = 0;
167 |
168 | const available = compressedData.getBytesAvailable();
169 | const blocks = (available / blockSize) | 0;
170 | // Number of samples in full blocks.
171 | const fullBlocks = (blocks * (2 * (blockSize - 4))) + 1;
172 | // Number of samples in the last incomplete block. 0 if the last block
173 | // is full.
174 | const subBlock = Math.max((available % blockSize) - 4, 0) * 2;
175 | // 1 if the last block is incomplete. 0 if it is complete.
176 | const incompleteBlock = Math.min(available % blockSize, 1);
177 | return fullBlocks + subBlock + incompleteBlock;
178 | }
179 |
180 | /**
181 | * Decompress sample data using the IMA ADPCM algorithm.
182 | * Note: Handles only one channel, 4-bits per sample.
183 | * @param {ArrayBufferStream} compressedData - a stream of compressed audio samples
184 | * @param {number} blockSize - the number of bytes in the stream
185 | * @param {Float32Array} out - the uncompressed audio samples
186 | */
187 | imaDecompress (compressedData, blockSize, out) {
188 | let sample;
189 | let code;
190 | let delta;
191 | let index = 0;
192 | let lastByte = -1; // -1 indicates that there is no saved lastByte
193 |
194 | // Bail and return no samples if we have no data
195 | if (!compressedData) return;
196 |
197 | compressedData.position = 0;
198 |
199 | const size = out.length;
200 | const samplesAfterBlockHeader = (blockSize - 4) * 2;
201 |
202 | const DELTA_TABLE = deltaTable();
203 |
204 | let i = 0;
205 | while (i < size) {
206 | // read block header
207 | sample = compressedData.readInt16();
208 | index = compressedData.readUint8();
209 | compressedData.position++; // skip extra header byte
210 | if (index > 88) index = 88;
211 | out[i++] = sample / 32768;
212 |
213 | const blockLength = Math.min(samplesAfterBlockHeader, size - i);
214 | const blockStart = i;
215 | while (i - blockStart < blockLength) {
216 | // read 4-bit code and compute delta from previous sample
217 | lastByte = compressedData.readUint8();
218 | code = lastByte & 0xF;
219 | delta = DELTA_TABLE[(index * 16) + code];
220 | // compute next index
221 | index += INDEX_TABLE[code];
222 | if (index > 88) index = 88;
223 | else if (index < 0) index = 0;
224 | // compute and output sample
225 | sample += delta;
226 | if (sample > 32767) sample = 32767;
227 | else if (sample < -32768) sample = -32768;
228 | out[i++] = sample / 32768;
229 |
230 | // use 4-bit code from lastByte and compute delta from previous
231 | // sample
232 | code = (lastByte >> 4) & 0xF;
233 | delta = DELTA_TABLE[(index * 16) + code];
234 | // compute next index
235 | index += INDEX_TABLE[code];
236 | if (index > 88) index = 88;
237 | else if (index < 0) index = 0;
238 | // compute and output sample
239 | sample += delta;
240 | if (sample > 32767) sample = 32767;
241 | else if (sample < -32768) sample = -32768;
242 | out[i++] = sample / 32768;
243 | }
244 | }
245 | }
246 | }
247 |
248 | module.exports = ADPCMSoundDecoder;
249 |
--------------------------------------------------------------------------------
/src/ArrayBufferStream.js:
--------------------------------------------------------------------------------
1 | class ArrayBufferStream {
2 | /**
3 | * ArrayBufferStream wraps the built-in javascript ArrayBuffer, adding the ability to access
4 | * data in it like a stream, tracking its position.
5 | * You can request to read a value from the front of the array, and it will keep track of the position
6 | * within the byte array, so that successive reads are consecutive.
7 | * The available types to read include:
8 | * Uint8, Uint8String, Int16, Uint16, Int32, Uint32
9 | * @param {ArrayBuffer} arrayBuffer - array to use as a stream
10 | * @param {number} start - the start position in the raw buffer. position
11 | * will be relative to the start value.
12 | * @param {number} end - the end position in the raw buffer. length and
13 | * bytes available will be relative to the end value.
14 | * @param {ArrayBufferStream} parent - if passed reuses the parent's
15 | * internal objects
16 | * @constructor
17 | */
18 | constructor (
19 | arrayBuffer, start = 0, end = arrayBuffer.byteLength,
20 | {
21 | _uint8View = new Uint8Array(arrayBuffer)
22 | } = {}
23 | ) {
24 | /**
25 | * Raw data buffer for stream to read.
26 | * @type {ArrayBufferStream}
27 | */
28 | this.arrayBuffer = arrayBuffer;
29 |
30 | /**
31 | * Start position in arrayBuffer. Read values are relative to the start
32 | * in the arrayBuffer.
33 | * @type {number}
34 | */
35 | this.start = start;
36 |
37 | /**
38 | * End position in arrayBuffer. Length and bytes available are relative
39 | * to the start, end, and _position in the arrayBuffer;
40 | * @type {number};
41 | */
42 | this.end = end;
43 |
44 | /**
45 | * Cached Uint8Array view of the arrayBuffer. Heavily used for reading
46 | * Uint8 values and Strings from the stream.
47 | * @type {Uint8Array}
48 | */
49 | this._uint8View = _uint8View;
50 |
51 | /**
52 | * Raw position in the arrayBuffer relative to the beginning of the
53 | * arrayBuffer.
54 | * @type {number}
55 | */
56 | this._position = start;
57 | }
58 |
59 | /**
60 | * Return a new ArrayBufferStream that is a slice of the existing one
61 | * @param {number} length - the number of bytes of extract
62 | * @return {ArrayBufferStream} the extracted stream
63 | */
64 | extract (length) {
65 | return new ArrayBufferStream(this.arrayBuffer, this._position, this._position + length, this);
66 | }
67 |
68 | /**
69 | * @return {number} the length of the stream in bytes
70 | */
71 | getLength () {
72 | return this.end - this.start;
73 | }
74 |
75 | /**
76 | * @return {number} the number of bytes available after the current position in the stream
77 | */
78 | getBytesAvailable () {
79 | return this.end - this._position;
80 | }
81 |
82 | /**
83 | * Position relative to the start value in the arrayBuffer of this
84 | * ArrayBufferStream.
85 | * @type {number}
86 | */
87 | get position () {
88 | return this._position - this.start;
89 | }
90 |
91 | /**
92 | * Set the position to read from in the arrayBuffer.
93 | * @type {number}
94 | * @param {number} value - new value to set position to
95 | */
96 | set position (value) {
97 | this._position = value + this.start;
98 | }
99 |
100 | /**
101 | * Read an unsigned 8 bit integer from the stream
102 | * @return {number} the next 8 bit integer in the stream
103 | */
104 | readUint8 () {
105 | const val = this._uint8View[this._position];
106 | this._position += 1;
107 | return val;
108 | }
109 |
110 | /**
111 | * Read a sequence of bytes of the given length and convert to a string.
112 | * This is a convenience method for use with short strings.
113 | * @param {number} length - the number of bytes to convert
114 | * @return {string} a String made by concatenating the chars in the input
115 | */
116 | readUint8String (length) {
117 | const arr = this._uint8View;
118 | let str = '';
119 | const end = this._position + length;
120 | for (let i = this._position; i < end; i++) {
121 | str += String.fromCharCode(arr[i]);
122 | }
123 | this._position += length;
124 | return str;
125 | }
126 |
127 | /**
128 | * Read a 16 bit integer from the stream
129 | * @return {number} the next 16 bit integer in the stream
130 | */
131 | readInt16 () {
132 | const val = new Int16Array(this.arrayBuffer, this._position, 1)[0];
133 | this._position += 2; // one 16 bit int is 2 bytes
134 | return val;
135 | }
136 |
137 | /**
138 | * Read an unsigned 16 bit integer from the stream
139 | * @return {number} the next unsigned 16 bit integer in the stream
140 | */
141 | readUint16 () {
142 | const val = new Uint16Array(this.arrayBuffer, this._position, 1)[0];
143 | this._position += 2; // one 16 bit int is 2 bytes
144 | return val;
145 | }
146 |
147 | /**
148 | * Read a 32 bit integer from the stream
149 | * @return {number} the next 32 bit integer in the stream
150 | */
151 | readInt32 () {
152 | let val;
153 | if (this._position % 4 === 0) {
154 | val = new Int32Array(this.arrayBuffer, this._position, 1)[0];
155 | } else {
156 | // Cannot read Int32 directly out because offset is not multiple of 4
157 | // Need to slice out the values first
158 | val = new Int32Array(
159 | this.arrayBuffer.slice(this._position, this._position + 4)
160 | )[0];
161 | }
162 | this._position += 4; // one 32 bit int is 4 bytes
163 | return val;
164 | }
165 |
166 | /**
167 | * Read an unsigned 32 bit integer from the stream
168 | * @return {number} the next unsigned 32 bit integer in the stream
169 | */
170 | readUint32 () {
171 | const val = new Uint32Array(this.arrayBuffer, this._position, 1)[0];
172 | this._position += 4; // one 32 bit int is 4 bytes
173 | return val;
174 | }
175 | }
176 |
177 | module.exports = ArrayBufferStream;
178 |
--------------------------------------------------------------------------------
/src/AudioEngine.js:
--------------------------------------------------------------------------------
1 | const StartAudioContext = require('./StartAudioContext');
2 | const AudioContext = require('audio-context');
3 |
4 | const log = require('./log');
5 | const uid = require('./uid');
6 |
7 | const ADPCMSoundDecoder = require('./ADPCMSoundDecoder');
8 | const Loudness = require('./Loudness');
9 | const SoundPlayer = require('./SoundPlayer');
10 |
11 | const EffectChain = require('./effects/EffectChain');
12 | const PanEffect = require('./effects/PanEffect');
13 | const PitchEffect = require('./effects/PitchEffect');
14 | const VolumeEffect = require('./effects/VolumeEffect');
15 |
16 | const SoundBank = require('./SoundBank');
17 |
18 | /**
19 | * Wrapper to ensure that audioContext.decodeAudioData is a promise
20 | * @param {object} audioContext The current AudioContext
21 | * @param {ArrayBuffer} buffer Audio data buffer to decode
22 | * @return {Promise} A promise that resolves to the decoded audio
23 | */
24 | const decodeAudioData = function (audioContext, buffer) {
25 | // Check for newer promise-based API
26 | if (audioContext.decodeAudioData.length === 1) {
27 | return audioContext.decodeAudioData(buffer);
28 | }
29 | // Fall back to callback API
30 | return new Promise((resolve, reject) => {
31 | audioContext.decodeAudioData(buffer,
32 | decodedAudio => resolve(decodedAudio),
33 | error => reject(error)
34 | );
35 | });
36 | };
37 |
38 | /**
39 | * There is a single instance of the AudioEngine. It handles global audio
40 | * properties and effects, loads all the audio buffers for sounds belonging to
41 | * sprites.
42 | */
43 | class AudioEngine {
44 | constructor (audioContext = new AudioContext()) {
45 | /**
46 | * AudioContext to play and manipulate sounds with a graph of source
47 | * and effect nodes.
48 | * @type {AudioContext}
49 | */
50 | this.audioContext = audioContext;
51 | StartAudioContext(this.audioContext);
52 |
53 | /**
54 | * Master GainNode that all sounds plays through. Changing this node
55 | * will change the volume for all sounds.
56 | * @type {GainNode}
57 | */
58 | this.inputNode = this.audioContext.createGain();
59 | this.inputNode.connect(this.audioContext.destination);
60 |
61 | /**
62 | * a map of soundIds to audio buffers, holding sounds for all sprites
63 | * @type {Object}
64 | */
65 | this.audioBuffers = {};
66 |
67 | /**
68 | * A Loudness detector.
69 | * @type {Loudness}
70 | */
71 | this.loudness = null;
72 |
73 | /**
74 | * Array of effects applied in order, left to right,
75 | * Left is closest to input, Right is closest to output
76 | */
77 | this.effects = [PanEffect, PitchEffect, VolumeEffect];
78 | }
79 |
80 | /**
81 | * Current time in the AudioEngine.
82 | * @type {number}
83 | */
84 | get currentTime () {
85 | return this.audioContext.currentTime;
86 | }
87 |
88 | /**
89 | * Names of the audio effects.
90 | * @enum {string}
91 | */
92 | get EFFECT_NAMES () {
93 | return {
94 | pitch: 'pitch',
95 | pan: 'pan'
96 | };
97 | }
98 |
99 | /**
100 | * A short duration to transition audio prarameters.
101 | *
102 | * Used as a time constant for exponential transitions. A general value
103 | * must be large enough that it does not cute off lower frequency, or bass,
104 | * sounds. Human hearing lower limit is ~20Hz making a safe value 25
105 | * milliseconds or 0.025 seconds, where half of a 20Hz wave will play along
106 | * with the DECAY. Higher frequencies will play multiple waves during the
107 | * same amount of time and avoid clipping.
108 | *
109 | * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AudioParam/setTargetAtTime}
110 | * @const {number}
111 | */
112 | get DECAY_DURATION () {
113 | return 0.025;
114 | }
115 |
116 | /**
117 | * Some environments cannot smoothly change parameters immediately, provide
118 | * a small delay before decaying.
119 | *
120 | * @see {@link https://bugzilla.mozilla.org/show_bug.cgi?id=1228207}
121 | * @const {number}
122 | */
123 | get DECAY_WAIT () {
124 | return 0.05;
125 | }
126 |
127 | /**
128 | * Get the input node.
129 | * @return {AudioNode} - audio node that is the input for this effect
130 | */
131 | getInputNode () {
132 | return this.inputNode;
133 | }
134 |
135 | /**
136 | * Decode a sound, decompressing it into audio samples.
137 | * @param {object} sound - an object containing audio data and metadata for
138 | * a sound
139 | * @param {Buffer} sound.data - sound data loaded from scratch-storage
140 | * @returns {?Promise} - a promise which will resolve to the sound id and
141 | * buffer if decoded
142 | */
143 | _decodeSound (sound) {
144 | // Make a copy of the buffer because decoding detaches the original
145 | // buffer
146 | const bufferCopy1 = sound.data.buffer.slice(0);
147 |
148 | // todo: multiple decodings of the same buffer create duplicate decoded
149 | // copies in audioBuffers. Create a hash id of the buffer or deprecate
150 | // audioBuffers to avoid memory issues for large audio buffers.
151 | const soundId = uid();
152 |
153 | // Attempt to decode the sound using the browser's native audio data
154 | // decoder If that fails, attempt to decode as ADPCM
155 | const decoding = decodeAudioData(this.audioContext, bufferCopy1)
156 | .catch(() => {
157 | // If the file is empty, create an empty sound
158 | if (sound.data.length === 0) {
159 | return this._emptySound();
160 | }
161 |
162 | // The audio context failed to parse the sound data
163 | // we gave it, so try to decode as 'adpcm'
164 |
165 | // First we need to create another copy of our original data
166 | const bufferCopy2 = sound.data.buffer.slice(0);
167 | // Try decoding as adpcm
168 | return new ADPCMSoundDecoder(this.audioContext).decode(bufferCopy2)
169 | .catch(() => this._emptySound());
170 | })
171 | .then(
172 | buffer => ([soundId, buffer]),
173 | error => {
174 | log.warn('audio data could not be decoded', error);
175 | }
176 | );
177 |
178 | return decoding;
179 | }
180 |
181 | /**
182 | * An empty sound buffer, for use when we are unable to decode a sound file.
183 | * @returns {AudioBuffer} - an empty audio buffer.
184 | */
185 | _emptySound () {
186 | return this.audioContext.createBuffer(1, 1, this.audioContext.sampleRate);
187 | }
188 |
189 | /**
190 | * Decode a sound, decompressing it into audio samples.
191 | *
192 | * Store a reference to it the sound in the audioBuffers dictionary,
193 | * indexed by soundId.
194 | *
195 | * @param {object} sound - an object containing audio data and metadata for
196 | * a sound
197 | * @param {Buffer} sound.data - sound data loaded from scratch-storage
198 | * @returns {?Promise} - a promise which will resolve to the sound id
199 | */
200 | decodeSound (sound) {
201 | return this._decodeSound(sound)
202 | .then(([id, buffer]) => {
203 | this.audioBuffers[id] = buffer;
204 | return id;
205 | });
206 | }
207 |
208 | /**
209 | * Decode a sound, decompressing it into audio samples.
210 | *
211 | * Create a SoundPlayer instance that can be used to play the sound and
212 | * stop and fade out playback.
213 | *
214 | * @param {object} sound - an object containing audio data and metadata for
215 | * a sound
216 | * @param {Buffer} sound.data - sound data loaded from scratch-storage
217 | * @returns {?Promise} - a promise which will resolve to the buffer
218 | */
219 | decodeSoundPlayer (sound) {
220 | return this._decodeSound(sound)
221 | .then(([id, buffer]) => new SoundPlayer(this, {id, buffer}));
222 | }
223 |
224 | /**
225 | * Get the current loudness of sound received by the microphone.
226 | * Sound is measured in RMS and smoothed.
227 | * @return {number} loudness scaled 0 to 100
228 | */
229 | getLoudness () {
230 | // The microphone has not been set up, so try to connect to it
231 | if (!this.loudness) {
232 | this.loudness = new Loudness(this.audioContext);
233 | }
234 |
235 | return this.loudness.getLoudness();
236 | }
237 |
238 | /**
239 | * Create an effect chain.
240 | * @returns {EffectChain} chain of effects defined by this AudioEngine
241 | */
242 | createEffectChain () {
243 | const effects = new EffectChain(this, this.effects);
244 | effects.connect(this);
245 | return effects;
246 | }
247 |
248 | /**
249 | * Create a sound bank and effect chain.
250 | * @returns {SoundBank} a sound bank configured with an effect chain
251 | * defined by this AudioEngine
252 | */
253 | createBank () {
254 | return new SoundBank(this, this.createEffectChain());
255 | }
256 | }
257 |
258 | module.exports = AudioEngine;
259 |
--------------------------------------------------------------------------------
/src/Loudness.js:
--------------------------------------------------------------------------------
1 | const log = require('./log');
2 |
3 | class Loudness {
4 | /**
5 | * Instrument and detect a loudness value from a local microphone.
6 | * @param {AudioContext} audioContext - context to create nodes from for
7 | * detecting loudness
8 | * @constructor
9 | */
10 | constructor (audioContext) {
11 | /**
12 | * AudioContext the mic will connect to and provide analysis of
13 | * @type {AudioContext}
14 | */
15 | this.audioContext = audioContext;
16 |
17 | /**
18 | * Are we connecting to the mic yet?
19 | * @type {Boolean}
20 | */
21 | this.connectingToMic = false;
22 |
23 | /**
24 | * microphone, for measuring loudness, with a level meter analyzer
25 | * @type {MediaStreamSourceNode}
26 | */
27 | this.mic = null;
28 | }
29 |
30 | /**
31 | * Get the current loudness of sound received by the microphone.
32 | * Sound is measured in RMS and smoothed.
33 | * Some code adapted from Tone.js: https://github.com/Tonejs/Tone.js
34 | * @return {number} loudness scaled 0 to 100
35 | */
36 | getLoudness () {
37 | // The microphone has not been set up, so try to connect to it
38 | if (!this.mic && !this.connectingToMic) {
39 | this.connectingToMic = true; // prevent multiple connection attempts
40 | navigator.mediaDevices.getUserMedia({audio: true}).then(stream => {
41 | this.audioStream = stream;
42 | this.mic = this.audioContext.createMediaStreamSource(stream);
43 | this.analyser = this.audioContext.createAnalyser();
44 | this.mic.connect(this.analyser);
45 | this.micDataArray = new Float32Array(this.analyser.fftSize);
46 | })
47 | .catch(err => {
48 | log.warn(err);
49 | });
50 | }
51 |
52 | // If the microphone is set up and active, measure the loudness
53 | if (this.mic && this.audioStream.active) {
54 | this.analyser.getFloatTimeDomainData(this.micDataArray);
55 | let sum = 0;
56 | // compute the RMS of the sound
57 | for (let i = 0; i < this.micDataArray.length; i++){
58 | sum += Math.pow(this.micDataArray[i], 2);
59 | }
60 | let rms = Math.sqrt(sum / this.micDataArray.length);
61 | // smooth the value, if it is descending
62 | if (this._lastValue) {
63 | rms = Math.max(rms, this._lastValue * 0.6);
64 | }
65 | this._lastValue = rms;
66 |
67 | // Scale the measurement so it's more sensitive to quieter sounds
68 | rms *= 1.63;
69 | rms = Math.sqrt(rms);
70 | // Scale it up to 0-100 and round
71 | rms = Math.round(rms * 100);
72 | // Prevent it from going above 100
73 | rms = Math.min(rms, 100);
74 | return rms;
75 | }
76 |
77 | // if there is no microphone input, return -1
78 | return -1;
79 | }
80 | }
81 |
82 | module.exports = Loudness;
83 |
--------------------------------------------------------------------------------
/src/SoundBank.js:
--------------------------------------------------------------------------------
1 | const log = require('./log');
2 |
3 | /**
4 | * A symbol indicating all targets are to be effected.
5 | * @const {string}
6 | */
7 | const ALL_TARGETS = '*';
8 |
9 | class SoundBank {
10 | /**
11 | * A bank of sounds that can be played.
12 | * @constructor
13 | * @param {AudioEngine} audioEngine - related AudioEngine
14 | * @param {EffectChain} effectChainPrime - original EffectChain cloned for
15 | * playing sounds
16 | */
17 | constructor (audioEngine, effectChainPrime) {
18 | /**
19 | * AudioEngine this SoundBank is related to.
20 | * @type {AudioEngine}
21 | */
22 | this.audioEngine = audioEngine;
23 |
24 | /**
25 | * Map of ids to soundPlayers.
26 | * @type {object}
27 | */
28 | this.soundPlayers = {};
29 |
30 | /**
31 | * Map of targets by sound id.
32 | * @type {Map}
33 | */
34 | this.playerTargets = new Map();
35 |
36 | /**
37 | * Map of effect chains by sound id.
38 | * @type {Map {
115 | if (playerTarget === target) {
116 | this.getSoundEffects(key).setEffectsFromTarget(target);
117 | }
118 | });
119 | }
120 |
121 | /**
122 | * Stop playback of sound by id if was lasted played by the target.
123 | * @param {Target} target - target to check if it last played the sound
124 | * @param {string} soundId - id of the sound to stop
125 | */
126 | stop (target, soundId) {
127 | if (this.playerTargets.get(soundId) === target) {
128 | this.soundPlayers[soundId].stop();
129 | }
130 | }
131 |
132 | /**
133 | * Stop all sounds for all targets or a specific target.
134 | * @param {Target|string} target - a symbol for all targets or the target
135 | * to stop sounds for
136 | */
137 | stopAllSounds (target = ALL_TARGETS) {
138 | this.playerTargets.forEach((playerTarget, key) => {
139 | if (target === ALL_TARGETS || playerTarget === target) {
140 | this.getSoundPlayer(key).stop();
141 | }
142 | });
143 | }
144 |
145 | /**
146 | * Dispose of all EffectChains and SoundPlayers.
147 | */
148 | dispose () {
149 | this.playerTargets.clear();
150 | this.soundEffects.forEach(effects => effects.dispose());
151 | this.soundEffects.clear();
152 | for (const soundId in this.soundPlayers) {
153 | if (Object.prototype.hasOwnProperty.call(this.soundPlayers, soundId)) {
154 | this.soundPlayers[soundId].dispose();
155 | }
156 | }
157 | this.soundPlayers = {};
158 | }
159 |
160 | }
161 |
162 | module.exports = SoundBank;
163 |
--------------------------------------------------------------------------------
/src/SoundPlayer.js:
--------------------------------------------------------------------------------
1 | const {EventEmitter} = require('events');
2 |
3 | const VolumeEffect = require('./effects/VolumeEffect');
4 |
5 | /**
6 | * Name of event that indicates playback has ended.
7 | * @const {string}
8 | */
9 | const ON_ENDED = 'ended';
10 |
11 | class SoundPlayer extends EventEmitter {
12 | /**
13 | * Play sounds that stop without audible clipping.
14 | *
15 | * @param {AudioEngine} audioEngine - engine to play sounds on
16 | * @param {object} data - required data for sound playback
17 | * @param {string} data.id - a unique id for this sound
18 | * @param {ArrayBuffer} data.buffer - buffer of the sound's waveform to play
19 | * @constructor
20 | */
21 | constructor (audioEngine, {id, buffer}) {
22 | super();
23 |
24 | /**
25 | * Unique sound identifier set by AudioEngine.
26 | * @type {string}
27 | */
28 | this.id = id;
29 |
30 | /**
31 | * AudioEngine creating this sound player.
32 | * @type {AudioEngine}
33 | */
34 | this.audioEngine = audioEngine;
35 |
36 | /**
37 | * Decoded audio buffer from audio engine for playback.
38 | * @type {AudioBuffer}
39 | */
40 | this.buffer = buffer;
41 |
42 | /**
43 | * Output audio node.
44 | * @type {AudioNode}
45 | */
46 | this.outputNode = null;
47 |
48 | /**
49 | * VolumeEffect used to fade out playing sounds when stopping them.
50 | * @type {VolumeEffect}
51 | */
52 | this.volumeEffect = null;
53 |
54 |
55 | /**
56 | * Target engine, effect, or chain this player directly connects to.
57 | * @type {AudioEngine|Effect|EffectChain}
58 | */
59 | this.target = null;
60 |
61 | /**
62 | * Internally is the SoundPlayer initialized with at least its buffer
63 | * source node and output node.
64 | * @type {boolean}
65 | */
66 | this.initialized = false;
67 |
68 | /**
69 | * Is the sound playing or starting to play?
70 | * @type {boolean}
71 | */
72 | this.isPlaying = false;
73 |
74 | /**
75 | * Timestamp sound is expected to be starting playback until. Once the
76 | * future timestamp is reached the sound is considered to be playing
77 | * through the audio hardware and stopping should fade out instead of
78 | * cutting off playback.
79 | * @type {number}
80 | */
81 | this.startingUntil = 0;
82 |
83 | /**
84 | * Rate to play back the audio at.
85 | * @type {number}
86 | */
87 | this.playbackRate = 1;
88 |
89 | // handleEvent is a EventTarget api for the DOM, however the
90 | // web-audio-test-api we use uses an addEventListener that isn't
91 | // compatable with object and requires us to pass this bound function
92 | // instead
93 | this.handleEvent = this.handleEvent.bind(this);
94 | }
95 |
96 | /**
97 | * Is plaback currently starting?
98 | * @type {boolean}
99 | */
100 | get isStarting () {
101 | return this.isPlaying && this.startingUntil > this.audioEngine.currentTime;
102 | }
103 |
104 | /**
105 | * Handle any event we have told the output node to listen for.
106 | * @param {Event} event - dom event to handle
107 | */
108 | handleEvent (event) {
109 | if (event.type === ON_ENDED) {
110 | this.onEnded();
111 | }
112 | }
113 |
114 | /**
115 | * Event listener for when playback ends.
116 | */
117 | onEnded () {
118 | this.emit('stop');
119 |
120 | this.isPlaying = false;
121 | }
122 |
123 | /**
124 | * Create the buffer source node during initialization or secondary
125 | * playback.
126 | */
127 | _createSource () {
128 | if (this.outputNode !== null) {
129 | this.outputNode.removeEventListener(ON_ENDED, this.handleEvent);
130 | this.outputNode.disconnect();
131 | }
132 |
133 | this.outputNode = this.audioEngine.audioContext.createBufferSource();
134 | this.outputNode.playbackRate.value = this.playbackRate;
135 | this.outputNode.buffer = this.buffer;
136 |
137 | this.outputNode.addEventListener(ON_ENDED, this.handleEvent);
138 |
139 | if (this.target !== null) {
140 | this.connect(this.target);
141 | }
142 | }
143 |
144 | /**
145 | * Initialize the player for first playback.
146 | */
147 | initialize () {
148 | this.initialized = true;
149 |
150 | this._createSource();
151 | }
152 |
153 | /**
154 | * Connect the player to the engine or an effect chain.
155 | * @param {object} target - object to connect to
156 | * @returns {object} - return this sound player
157 | */
158 | connect (target) {
159 | if (target === this.volumeEffect) {
160 | this.outputNode.disconnect();
161 | this.outputNode.connect(this.volumeEffect.getInputNode());
162 | return;
163 | }
164 |
165 | this.target = target;
166 |
167 | if (!this.initialized) {
168 | return;
169 | }
170 |
171 | if (this.volumeEffect === null) {
172 | this.outputNode.disconnect();
173 | this.outputNode.connect(target.getInputNode());
174 | } else {
175 | this.volumeEffect.connect(target);
176 | }
177 |
178 | return this;
179 | }
180 |
181 | /**
182 | * Teardown the player.
183 | */
184 | dispose () {
185 | if (!this.initialized) {
186 | return;
187 | }
188 |
189 | this.stopImmediately();
190 |
191 | if (this.volumeEffect !== null) {
192 | this.volumeEffect.dispose();
193 | this.volumeEffect = null;
194 | }
195 |
196 | this.outputNode.disconnect();
197 | this.outputNode = null;
198 |
199 | this.target = null;
200 |
201 | this.initialized = false;
202 | }
203 |
204 | /**
205 | * Take the internal state of this player and create a new player from
206 | * that. Restore the state of this player to that before its first playback.
207 | *
208 | * The returned player can be used to stop the original playback or
209 | * continue it without manipulation from the original player.
210 | *
211 | * @returns {SoundPlayer} - new SoundPlayer with old state
212 | */
213 | take () {
214 | if (this.outputNode) {
215 | this.outputNode.removeEventListener(ON_ENDED, this.handleEvent);
216 | }
217 |
218 | const taken = new SoundPlayer(this.audioEngine, this);
219 | taken.playbackRate = this.playbackRate;
220 | if (this.isPlaying) {
221 | taken.startingUntil = this.startingUntil;
222 | taken.isPlaying = this.isPlaying;
223 | taken.initialized = this.initialized;
224 | taken.outputNode = this.outputNode;
225 | taken.outputNode.addEventListener(ON_ENDED, taken.handleEvent);
226 | taken.volumeEffect = this.volumeEffect;
227 | if (taken.volumeEffect) {
228 | taken.volumeEffect.audioPlayer = taken;
229 | }
230 | if (this.target !== null) {
231 | taken.connect(this.target);
232 | }
233 |
234 | this.emit('stop');
235 | taken.emit('play');
236 | }
237 |
238 | this.outputNode = null;
239 | this.volumeEffect = null;
240 | this.initialized = false;
241 | this.startingUntil = 0;
242 | this.isPlaying = false;
243 |
244 | return taken;
245 | }
246 |
247 | /**
248 | * Start playback for this sound.
249 | *
250 | * If the sound is already playing it will stop playback with a quick fade
251 | * out.
252 | */
253 | play () {
254 | if (this.isStarting) {
255 | this.emit('stop');
256 | this.emit('play');
257 | return;
258 | }
259 |
260 | if (this.isPlaying) {
261 | this.stop();
262 | }
263 |
264 | if (this.initialized) {
265 | this._createSource();
266 | } else {
267 | this.initialize();
268 | }
269 |
270 | this.outputNode.start();
271 |
272 | this.isPlaying = true;
273 |
274 | const {currentTime, DECAY_DURATION} = this.audioEngine;
275 | this.startingUntil = currentTime + DECAY_DURATION;
276 |
277 | this.emit('play');
278 | }
279 |
280 | /**
281 | * Stop playback after quickly fading out.
282 | */
283 | stop () {
284 | if (!this.isPlaying) {
285 | return;
286 | }
287 |
288 | // always do a manual stop on a taken / volume effect fade out sound
289 | // player take will emit "stop" as well as reset all of our playing
290 | // statuses / remove our nodes / etc
291 | const taken = this.take();
292 | taken.volumeEffect = new VolumeEffect(taken.audioEngine, taken, null);
293 |
294 | taken.volumeEffect.connect(taken.target);
295 | // volumeEffect will recursively connect to us if it needs to, so this
296 | // happens too:
297 | // taken.connect(taken.volumeEffect);
298 |
299 | taken.finished().then(() => taken.dispose());
300 |
301 | taken.volumeEffect.set(0);
302 | const {currentTime, DECAY_DURATION} = this.audioEngine;
303 | taken.outputNode.stop(currentTime + DECAY_DURATION);
304 | }
305 |
306 | /**
307 | * Stop immediately without fading out. May cause audible clipping.
308 | */
309 | stopImmediately () {
310 | if (!this.isPlaying) {
311 | return;
312 | }
313 |
314 | this.outputNode.stop();
315 |
316 | this.isPlaying = false;
317 | this.startingUntil = 0;
318 |
319 | this.emit('stop');
320 | }
321 |
322 | /**
323 | * Return a promise that resolves when the sound next finishes.
324 | * @returns {Promise} - resolves when the sound finishes
325 | */
326 | finished () {
327 | return new Promise(resolve => {
328 | this.once('stop', resolve);
329 | });
330 | }
331 |
332 | /**
333 | * Set the sound's playback rate.
334 | * @param {number} value - playback rate. Default is 1.
335 | */
336 | setPlaybackRate (value) {
337 | this.playbackRate = value;
338 |
339 | if (this.initialized) {
340 | this.outputNode.playbackRate.value = value;
341 | }
342 | }
343 | }
344 |
345 | module.exports = SoundPlayer;
346 |
--------------------------------------------------------------------------------
/src/StartAudioContext.js:
--------------------------------------------------------------------------------
1 | // StartAudioContext assumes that we are in a window/document setting and messes with the unit
2 | // tests, this is our own version just checking to see if we have a global document to listen
3 | // to before we even try to "start" it. Our test api audio context is started by default.
4 | const StartAudioContext = require('startaudiocontext');
5 |
6 | module.exports = function (context) {
7 | if (typeof document !== 'undefined') {
8 | return StartAudioContext(context);
9 | }
10 | };
11 |
--------------------------------------------------------------------------------
/src/effects/Effect.js:
--------------------------------------------------------------------------------
1 | /**
2 | * An effect on an AudioPlayer and all its SoundPlayers.
3 | */
4 | class Effect {
5 | /**
6 | * @param {AudioEngine} audioEngine - audio engine this runs with
7 | * @param {AudioPlayer} audioPlayer - audio player this affects
8 | * @param {Effect} lastEffect - effect in the chain before this one
9 | * @constructor
10 | */
11 | constructor (audioEngine, audioPlayer, lastEffect) {
12 | this.audioEngine = audioEngine;
13 | this.audioPlayer = audioPlayer;
14 | this.lastEffect = lastEffect;
15 |
16 | this.value = this.DEFAULT_VALUE;
17 |
18 | this.initialized = false;
19 |
20 | this.inputNode = null;
21 | this.outputNode = null;
22 |
23 | this.target = null;
24 | }
25 |
26 | /**
27 | * Return the name of the effect.
28 | * @type {string}
29 | */
30 | get name () {
31 | throw new Error(`${this.constructor.name}.name is not implemented`);
32 | }
33 |
34 | /**
35 | * Default value to set the Effect to when constructed and when clear'ed.
36 | * @const {number}
37 | */
38 | get DEFAULT_VALUE () {
39 | return 0;
40 | }
41 |
42 | /**
43 | * Should the effect be connected to the audio graph?
44 | * The pitch effect is an example that does not need to be patched in.
45 | * Instead of affecting the graph it affects the player directly.
46 | * @return {boolean} is the effect affecting the graph?
47 | */
48 | get _isPatch () {
49 | return this.initialized && (this.value !== this.DEFAULT_VALUE || this.audioPlayer === null);
50 | }
51 |
52 | /**
53 | * Get the input node.
54 | * @return {AudioNode} - audio node that is the input for this effect
55 | */
56 | getInputNode () {
57 | if (this._isPatch) {
58 | return this.inputNode;
59 | }
60 | return this.target.getInputNode();
61 | }
62 |
63 | /**
64 | * Initialize the Effect.
65 | * Effects start out uninitialized. Then initialize when they are first set
66 | * with some value.
67 | * @throws {Error} throws when left unimplemented
68 | */
69 | initialize () {
70 | throw new Error(`${this.constructor.name}.initialize is not implemented.`);
71 | }
72 |
73 | /**
74 | * Set the effects value.
75 | * @private
76 | * @param {number} value - new value to set effect to
77 | */
78 | _set () {
79 | throw new Error(`${this.constructor.name}._set is not implemented.`);
80 | }
81 |
82 | /**
83 | * Set the effects value.
84 | * @param {number} value - new value to set effect to
85 | */
86 | set (value) {
87 | // Initialize the node on first set.
88 | if (!this.initialized) {
89 | this.initialize();
90 | }
91 |
92 | // Store whether the graph should currently affected by this effect.
93 | const wasPatch = this._isPatch;
94 | if (wasPatch) {
95 | this._lastPatch = this.audioEngine.currentTime;
96 | }
97 |
98 | // Call the internal implementation per this Effect.
99 | this._set(value);
100 |
101 | // Connect or disconnect from the graph if this now applies or no longer
102 | // applies an effect.
103 | if (this._isPatch !== wasPatch && this.target !== null) {
104 | this.connect(this.target);
105 | }
106 | }
107 |
108 | /**
109 | * Update the effect for changes in the audioPlayer.
110 | */
111 | update () {}
112 |
113 | /**
114 | * Clear the value back to the default.
115 | */
116 | clear () {
117 | this.set(this.DEFAULT_VALUE);
118 | }
119 |
120 | /**
121 | * Connnect this effect's output to another audio node
122 | * @param {object} target - target whose node to should be connected
123 | */
124 | connect (target) {
125 | if (target === null) {
126 | throw new Error('target may not be null');
127 | }
128 |
129 | const checkForCircularReference = subtarget => {
130 | if (subtarget) {
131 | if (subtarget === this) {
132 | return true;
133 | }
134 | return checkForCircularReference(subtarget.target);
135 | }
136 | };
137 | if (checkForCircularReference(target)) {
138 | throw new Error('Effect cannot connect to itself');
139 | }
140 |
141 | this.target = target;
142 |
143 | if (this.outputNode !== null) {
144 | this.outputNode.disconnect();
145 | }
146 |
147 | if (this._isPatch || this._lastPatch + this.audioEngine.DECAY_DURATION < this.audioEngine.currentTime) {
148 | this.outputNode.connect(target.getInputNode());
149 | }
150 |
151 | if (this.lastEffect === null) {
152 | if (this.audioPlayer !== null) {
153 | this.audioPlayer.connect(this);
154 | }
155 | } else {
156 | this.lastEffect.connect(this);
157 | }
158 | }
159 |
160 | /**
161 | * Clean up and disconnect audio nodes.
162 | */
163 | dispose () {
164 | this.inputNode = null;
165 | this.outputNode = null;
166 | this.target = null;
167 |
168 | this.initialized = false;
169 | }
170 | }
171 |
172 | module.exports = Effect;
173 |
--------------------------------------------------------------------------------
/src/effects/EffectChain.js:
--------------------------------------------------------------------------------
1 | class EffectChain {
2 | /**
3 | * Chain of effects that can be applied to a group of SoundPlayers.
4 | * @param {AudioEngine} audioEngine - engine whose effects these belong to
5 | * @param {Array} effects - array of Effect classes to construct
6 | */
7 | constructor (audioEngine, effects) {
8 | /**
9 | * AudioEngine whose effects these belong to.
10 | * @type {AudioEngine}
11 | */
12 | this.audioEngine = audioEngine;
13 |
14 | /**
15 | * Node incoming connections will attach to. This node than connects to
16 | * the items in the chain which finally connect to some output.
17 | * @type {AudioNode}
18 | */
19 | this.inputNode = this.audioEngine.audioContext.createGain();
20 |
21 | /**
22 | * List of Effect types to create.
23 | * @type {Array}
24 | */
25 | this.effects = effects;
26 |
27 | // Effects are instantiated in reverse so that the first refers to the
28 | // second, the second refers to the third, etc and the last refers to
29 | // null.
30 | let lastEffect = null;
31 | /**
32 | * List of instantiated Effects.
33 | * @type {Array}
34 | */
35 | this._effects = effects
36 | .reverse()
37 | .map(Effect => {
38 | const effect = new Effect(audioEngine, this, lastEffect);
39 | this[effect.name] = effect;
40 | lastEffect = effect;
41 | return effect;
42 | })
43 | .reverse();
44 |
45 | /**
46 | * First effect of this chain.
47 | * @type {Effect}
48 | */
49 | this.firstEffect = this._effects[0];
50 |
51 | /**
52 | * Last effect of this chain.
53 | * @type {Effect}
54 | */
55 | this.lastEffect = this._effects[this._effects.length - 1];
56 |
57 | /**
58 | * A set of players this chain is managing.
59 | */
60 | this._soundPlayers = new Set();
61 | }
62 |
63 | /**
64 | * Create a clone of the EffectChain.
65 | * @returns {EffectChain} a clone of this EffectChain
66 | */
67 | clone () {
68 | const chain = new EffectChain(this.audioEngine, this.effects);
69 | if (this.target) {
70 | chain.connect(this.target);
71 | }
72 | return chain;
73 | }
74 |
75 | /**
76 | * Add a sound player.
77 | * @param {SoundPlayer} soundPlayer - a sound player to manage
78 | */
79 | addSoundPlayer (soundPlayer) {
80 | if (!this._soundPlayers.has(soundPlayer)) {
81 | this._soundPlayers.add(soundPlayer);
82 | this.update();
83 | }
84 | }
85 |
86 | /**
87 | * Remove a sound player.
88 | * @param {SoundPlayer} soundPlayer - a sound player to stop managing
89 | */
90 | removeSoundPlayer (soundPlayer) {
91 | this._soundPlayers.remove(soundPlayer);
92 | }
93 |
94 | /**
95 | * Get the audio input node.
96 | * @returns {AudioNode} audio node the upstream can connect to
97 | */
98 | getInputNode () {
99 | return this.inputNode;
100 | }
101 |
102 | /**
103 | * Connnect this player's output to another audio node.
104 | * @param {object} target - target whose node to should be connected
105 | */
106 | connect (target) {
107 | const {firstEffect, lastEffect} = this;
108 |
109 | if (target === lastEffect) {
110 | this.inputNode.disconnect();
111 | this.inputNode.connect(lastEffect.getInputNode());
112 |
113 | return;
114 | } else if (target === firstEffect) {
115 | return;
116 | }
117 |
118 | this.target = target;
119 |
120 | firstEffect.connect(target);
121 | }
122 |
123 | /**
124 | * Array of SoundPlayers managed by this EffectChain.
125 | * @returns {Array} sound players managed by this chain
126 | */
127 | getSoundPlayers () {
128 | return [...this._soundPlayers];
129 | }
130 |
131 | /**
132 | * Set Effect values with named values on target.soundEffects if it exist
133 | * and then from target itself.
134 | * @param {Target} target - target to set values from
135 | */
136 | setEffectsFromTarget (target) {
137 | this._effects.forEach(effect => {
138 | if ('soundEffects' in target && effect.name in target.soundEffects) {
139 | effect.set(target.soundEffects[effect.name]);
140 | } else if (effect.name in target) {
141 | effect.set(target[effect.name]);
142 | }
143 | });
144 | }
145 |
146 | /**
147 | * Set an effect value by its name.
148 | * @param {string} effect - effect name to change
149 | * @param {number} value - value to set effect to
150 | */
151 | set (effect, value) {
152 | if (effect in this) {
153 | this[effect].set(value);
154 | }
155 | }
156 |
157 | /**
158 | * Update managed sound players with the effects on this chain.
159 | */
160 | update () {
161 | this._effects.forEach(effect => effect.update());
162 | }
163 |
164 | /**
165 | * Clear all effects to their default values.
166 | */
167 | clear () {
168 | this._effects.forEach(effect => effect.clear());
169 | }
170 |
171 | /**
172 | * Dispose of all effects in this chain. Nothing is done to managed
173 | * SoundPlayers.
174 | */
175 | dispose () {
176 | this._soundPlayers = null;
177 | this._effects.forEach(effect => effect.dispose());
178 | this._effects = null;
179 | }
180 | }
181 |
182 | module.exports = EffectChain;
183 |
--------------------------------------------------------------------------------
/src/effects/PanEffect.js:
--------------------------------------------------------------------------------
1 | const Effect = require('./Effect');
2 |
3 | /**
4 | * A pan effect, which moves the sound to the left or right between the speakers
5 | * Effect value of -100 puts the audio entirely on the left channel,
6 | * 0 centers it, 100 puts it on the right.
7 | */
8 | class PanEffect extends Effect {
9 | /**
10 | * @param {AudioEngine} audioEngine - audio engine this runs with
11 | * @param {AudioPlayer} audioPlayer - audio player this affects
12 | * @param {Effect} lastEffect - effect in the chain before this one
13 | * @constructor
14 | */
15 | constructor (audioEngine, audioPlayer, lastEffect) {
16 | super(audioEngine, audioPlayer, lastEffect);
17 |
18 | this.leftGain = null;
19 | this.rightGain = null;
20 | this.channelMerger = null;
21 | }
22 |
23 | /**
24 | * Return the name of the effect.
25 | * @type {string}
26 | */
27 | get name () {
28 | return 'pan';
29 | }
30 |
31 | /**
32 | * Initialize the Effect.
33 | * Effects start out uninitialized. Then initialize when they are first set
34 | * with some value.
35 | * @throws {Error} throws when left unimplemented
36 | */
37 | initialize () {
38 | const audioContext = this.audioEngine.audioContext;
39 |
40 | this.inputNode = audioContext.createGain();
41 | this.leftGain = audioContext.createGain();
42 | this.rightGain = audioContext.createGain();
43 | this.channelMerger = audioContext.createChannelMerger(2);
44 | this.outputNode = this.channelMerger;
45 |
46 | this.inputNode.connect(this.leftGain);
47 | this.inputNode.connect(this.rightGain);
48 | this.leftGain.connect(this.channelMerger, 0, 0);
49 | this.rightGain.connect(this.channelMerger, 0, 1);
50 |
51 | this.initialized = true;
52 | }
53 |
54 | /**
55 | * Set the effect value
56 | * @param {number} value - the new value to set the effect to
57 | */
58 | _set (value) {
59 | this.value = value;
60 |
61 | // Map the scratch effect value (-100 to 100) to (0 to 1)
62 | const p = (value + 100) / 200;
63 |
64 | // Use trig functions for equal-loudness panning
65 | // See e.g. https://docs.cycling74.com/max7/tutorials/13_panningchapter01
66 | const leftVal = Math.cos(p * Math.PI / 2);
67 | const rightVal = Math.sin(p * Math.PI / 2);
68 |
69 | const {currentTime, DECAY_WAIT, DECAY_DURATION} = this.audioEngine;
70 | this.leftGain.gain.setTargetAtTime(leftVal, currentTime + DECAY_WAIT, DECAY_DURATION);
71 | this.rightGain.gain.setTargetAtTime(rightVal, currentTime + DECAY_WAIT, DECAY_DURATION);
72 | }
73 |
74 | /**
75 | * Clean up and disconnect audio nodes.
76 | */
77 | dispose () {
78 | if (!this.initialized) {
79 | return;
80 | }
81 |
82 | this.inputNode.disconnect();
83 | this.leftGain.disconnect();
84 | this.rightGain.disconnect();
85 | this.channelMerger.disconnect();
86 |
87 | this.inputNode = null;
88 | this.leftGain = null;
89 | this.rightGain = null;
90 | this.channelMerger = null;
91 | this.outputNode = null;
92 | this.target = null;
93 |
94 | this.initialized = false;
95 | }
96 | }
97 |
98 | module.exports = PanEffect;
99 |
--------------------------------------------------------------------------------
/src/effects/PitchEffect.js:
--------------------------------------------------------------------------------
1 | const Effect = require('./Effect');
2 |
3 | /**
4 | * A pitch change effect, which changes the playback rate of the sound in order
5 | * to change its pitch: reducing the playback rate lowers the pitch, increasing
6 | * the rate raises the pitch. The duration of the sound is also changed.
7 | *
8 | * Changing the value of the pitch effect by 10 causes a change in pitch by 1
9 | * semitone (i.e. a musical half-step, such as the difference between C and C#)
10 | * Changing the pitch effect by 120 changes the pitch by one octave (12
11 | * semitones)
12 | *
13 | * The value of this effect is not clamped (i.e. it is typically between -120
14 | * and 120, but can be set much higher or much lower, with weird and fun
15 | * results). We should consider what extreme values to use for clamping it.
16 | *
17 | * Note that this effect functions differently from the other audio effects. It
18 | * is not part of a chain of audio nodes. Instead, it provides a way to set the
19 | * playback on one SoundPlayer or a group of them.
20 | */
21 | class PitchEffect extends Effect {
22 | /**
23 | * @param {AudioEngine} audioEngine - audio engine this runs with
24 | * @param {AudioPlayer} audioPlayer - audio player this affects
25 | * @param {Effect} lastEffect - effect in the chain before this one
26 | * @constructor
27 | */
28 | constructor (audioEngine, audioPlayer, lastEffect) {
29 | super(audioEngine, audioPlayer, lastEffect);
30 |
31 | /**
32 | * The playback rate ratio
33 | * @type {Number}
34 | */
35 | this.ratio = 1;
36 | }
37 |
38 | /**
39 | * Return the name of the effect.
40 | * @type {string}
41 | */
42 | get name () {
43 | return 'pitch';
44 | }
45 |
46 | /**
47 | * Should the effect be connected to the audio graph?
48 | * @return {boolean} is the effect affecting the graph?
49 | */
50 | get _isPatch () {
51 | return false;
52 | }
53 |
54 | /**
55 | * Get the input node.
56 | * @return {AudioNode} - audio node that is the input for this effect
57 | */
58 | getInputNode () {
59 | return this.target.getInputNode();
60 | }
61 |
62 | /**
63 | * Initialize the Effect.
64 | * Effects start out uninitialized. Then initialize when they are first set
65 | * with some value.
66 | * @throws {Error} throws when left unimplemented
67 | */
68 | initialize () {
69 | this.initialized = true;
70 | }
71 |
72 | /**
73 | * Set the effect value.
74 | * @param {number} value - the new value to set the effect to
75 | */
76 | _set (value) {
77 | this.value = value;
78 | this.ratio = this.getRatio(this.value);
79 | this.updatePlayers(this.audioPlayer.getSoundPlayers());
80 | }
81 |
82 | /**
83 | * Update the effect for changes in the audioPlayer.
84 | */
85 | update () {
86 | this.updatePlayers(this.audioPlayer.getSoundPlayers());
87 | }
88 |
89 | /**
90 | * Compute the playback ratio for an effect value.
91 | * The playback ratio is scaled so that a change of 10 in the effect value
92 | * gives a change of 1 semitone in the ratio.
93 | * @param {number} val - an effect value
94 | * @returns {number} a playback ratio
95 | */
96 | getRatio (val) {
97 | const interval = val / 10;
98 | // Convert the musical interval in semitones to a frequency ratio
99 | return Math.pow(2, (interval / 12));
100 | }
101 |
102 | /**
103 | * Update a sound player's playback rate using the current ratio for the
104 | * effect
105 | * @param {object} player - a SoundPlayer object
106 | */
107 | updatePlayer (player) {
108 | player.setPlaybackRate(this.ratio);
109 | }
110 |
111 | /**
112 | * Update a sound player's playback rate using the current ratio for the
113 | * effect
114 | * @param {object} players - a dictionary of SoundPlayer objects to update,
115 | * indexed by md5
116 | */
117 | updatePlayers (players) {
118 | if (!players) return;
119 |
120 | for (const id in players) {
121 | if (Object.prototype.hasOwnProperty.call(players, id)) {
122 | this.updatePlayer(players[id]);
123 | }
124 | }
125 | }
126 | }
127 |
128 | module.exports = PitchEffect;
129 |
--------------------------------------------------------------------------------
/src/effects/VolumeEffect.js:
--------------------------------------------------------------------------------
1 | const Effect = require('./Effect');
2 |
3 | /**
4 | * Affect the volume of an effect chain.
5 | */
6 | class VolumeEffect extends Effect {
7 | /**
8 | * Default value to set the Effect to when constructed and when clear'ed.
9 | * @const {number}
10 | */
11 | get DEFAULT_VALUE () {
12 | return 100;
13 | }
14 |
15 | /**
16 | * Return the name of the effect.
17 | * @type {string}
18 | */
19 | get name () {
20 | return 'volume';
21 | }
22 |
23 | /**
24 | * Initialize the Effect.
25 | * Effects start out uninitialized. Then initialize when they are first set
26 | * with some value.
27 | * @throws {Error} throws when left unimplemented
28 | */
29 | initialize () {
30 | this.inputNode = this.audioEngine.audioContext.createGain();
31 | this.outputNode = this.inputNode;
32 |
33 | this.initialized = true;
34 | }
35 |
36 | /**
37 | * Set the effects value.
38 | * @private
39 | * @param {number} value - new value to set effect to
40 | */
41 | _set (value) {
42 | this.value = value;
43 |
44 | const {gain} = this.outputNode;
45 | const {currentTime, DECAY_DURATION} = this.audioEngine;
46 | gain.linearRampToValueAtTime(value / 100, currentTime + DECAY_DURATION);
47 | }
48 |
49 | /**
50 | * Clean up and disconnect audio nodes.
51 | */
52 | dispose () {
53 | if (!this.initialized) {
54 | return;
55 | }
56 |
57 | this.outputNode.disconnect();
58 |
59 | this.inputNode = null;
60 | this.outputNode = null;
61 | this.target = null;
62 |
63 | this.initialized = false;
64 | }
65 | }
66 |
67 | module.exports = VolumeEffect;
68 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @fileOverview Scratch Audio is divided into a single AudioEngine, that
3 | * handles global functionality, and AudioPlayers, belonging to individual
4 | * sprites and clones.
5 | */
6 |
7 | const AudioEngine = require('./AudioEngine');
8 |
9 | module.exports = AudioEngine;
10 |
--------------------------------------------------------------------------------
/src/log.js:
--------------------------------------------------------------------------------
1 | const minilog = require('minilog');
2 | minilog.enable();
3 |
4 | module.exports = minilog('scratch-audioengine');
5 |
--------------------------------------------------------------------------------
/src/uid.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @fileoverview UID generator, from Blockly.
3 | */
4 |
5 | /**
6 | * Legal characters for the unique ID.
7 | * Should be all on a US keyboard. No XML special characters or control codes.
8 | * Removed $ due to issue 251.
9 | * @private
10 | */
11 | const soup_ = '!#%()*+,-./:;=?@[]^_`{|}~' +
12 | 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
13 |
14 | /**
15 | * Generate a unique ID, from Blockly. This should be globally unique.
16 | * 87 characters ^ 20 length > 128 bits (better than a UUID).
17 | * @return {string} A globally unique ID string.
18 | */
19 | const uid = function () {
20 | const length = 20;
21 | const soupLength = soup_.length;
22 | const id = [];
23 | for (let i = 0; i < length; i++) {
24 | id[i] = soup_.charAt(Math.random() * soupLength);
25 | }
26 | return id.join('');
27 | };
28 |
29 | module.exports = uid;
30 |
--------------------------------------------------------------------------------
/test/AudioEngine.js:
--------------------------------------------------------------------------------
1 | const tap = require('tap');
2 | const AudioEngine = require('../src/AudioEngine');
3 |
4 | const {AudioContext} = require('web-audio-test-api');
5 |
6 | tap.test('AudioEngine', t => {
7 | const audioEngine = new AudioEngine(new AudioContext());
8 |
9 | t.plan(1);
10 | t.deepEqual(audioEngine.inputNode.toJSON(), {
11 | gain: {
12 | inputs: [],
13 | value: 1
14 | },
15 | inputs: [],
16 | name: 'GainNode'
17 | }, 'JSON Representation of inputNode');
18 | });
19 |
--------------------------------------------------------------------------------
/test/SoundPlayer.js:
--------------------------------------------------------------------------------
1 | /* global Uint8Array Promise */
2 | const tap = require('tap');
3 | const {AudioContext} = require('web-audio-test-api');
4 |
5 | const AudioEngine = require('../src/AudioEngine');
6 |
7 |
8 | tap.test('SoundPlayer', suite => {
9 |
10 | let audioContext;
11 | let audioEngine;
12 | let soundPlayer;
13 |
14 | const help = {
15 | get engineInputs () {
16 | return audioEngine.inputNode.toJSON().inputs;
17 | }
18 | };
19 |
20 | suite.beforeEach(() => {
21 | audioContext = new AudioContext();
22 | audioEngine = new AudioEngine(audioContext);
23 | // sound will be 0.2 seconds long
24 | audioContext.DECODE_AUDIO_DATA_RESULT = audioContext.createBuffer(2, 8820, 44100);
25 | audioContext.DECODE_AUDIO_DATA_FAILED = false;
26 | const data = new Uint8Array(0);
27 | return audioEngine.decodeSoundPlayer({data}).then(result => {
28 | soundPlayer = result;
29 | });
30 | });
31 |
32 | suite.afterEach(() => {
33 | soundPlayer.dispose();
34 | soundPlayer = null;
35 | audioEngine = null;
36 | audioContext.$reset();
37 | audioContext = null;
38 | });
39 |
40 | suite.plan(5);
41 |
42 | suite.test('play initializes and creates source node', t => {
43 | t.plan(3);
44 | t.equal(soundPlayer.initialized, false, 'not yet initialized');
45 | soundPlayer.play();
46 | t.equal(soundPlayer.initialized, true, 'now is initialized');
47 | t.deepEqual(soundPlayer.outputNode.toJSON(), {
48 | buffer: audioContext.DECODE_AUDIO_DATA_RESULT.toJSON(),
49 | inputs: [],
50 | loop: false,
51 | loopEnd: 0,
52 | loopStart: 0,
53 | name: 'AudioBufferSourceNode',
54 | playbackRate: {
55 | inputs: [],
56 | value: 1
57 | }
58 | });
59 |
60 | t.end();
61 | });
62 |
63 | suite.test('connect', t => {
64 | t.plan(1);
65 | soundPlayer.play();
66 | soundPlayer.connect(audioEngine);
67 | t.deepEqual(help.engineInputs, [
68 | soundPlayer.outputNode.toJSON()
69 | ], 'output node connects to input node');
70 | t.end();
71 | });
72 |
73 | suite.test('stop decay', t => {
74 | t.plan(5);
75 | soundPlayer.play();
76 | soundPlayer.connect(audioEngine);
77 | const outputNode = soundPlayer.outputNode;
78 |
79 | audioContext.$processTo(0);
80 | soundPlayer.stop();
81 | t.equal(soundPlayer.outputNode, null, 'nullify outputNode immediately (taken sound is stopping)');
82 | t.deepEqual(help.engineInputs, [{
83 | name: 'GainNode',
84 | gain: {
85 | value: 1,
86 | inputs: []
87 | },
88 | inputs: [outputNode.toJSON()]
89 | }], 'output node connects to gain node to input node');
90 |
91 | audioContext.$processTo(audioEngine.DECAY_DURATION / 2);
92 | t.equal(outputNode.$state, 'PLAYING');
93 |
94 | audioContext.$processTo(audioEngine.DECAY_DURATION + 0.001);
95 | t.deepEqual(help.engineInputs, [{
96 | name: 'GainNode',
97 | gain: {
98 | value: 0,
99 | inputs: []
100 | },
101 | inputs: [outputNode.toJSON()]
102 | }], 'output node connects to gain node to input node decayed');
103 |
104 | t.equal(outputNode.$state, 'FINISHED');
105 |
106 | t.end();
107 | });
108 |
109 | suite.test('play while playing debounces', t => {
110 | t.plan(7);
111 | const log = [];
112 | soundPlayer.connect(audioEngine);
113 | soundPlayer.play();
114 | t.equal(soundPlayer.isStarting, true, 'player.isStarting');
115 | const originalNode = soundPlayer.outputNode;
116 | // the second play should still "finish" this play
117 | soundPlayer.finished().then(() => log.push('finished first'));
118 | soundPlayer.play();
119 | soundPlayer.finished().then(() => log.push('finished second'));
120 | soundPlayer.play();
121 | soundPlayer.finished().then(() => log.push('finished third'));
122 | soundPlayer.play();
123 | t.equal(originalNode, soundPlayer.outputNode, 'same output node');
124 | t.equal(soundPlayer.outputNode.$state, 'PLAYING');
125 | return Promise.resolve().then(() => {
126 | t.deepEqual(log, ['finished first', 'finished second', 'finished third'], 'finished in order');
127 |
128 | // fast forward to one ms before decay time
129 | audioContext.$processTo(audioEngine.DECAY_DURATION - 0.001);
130 | soundPlayer.play();
131 |
132 | t.equal(originalNode, soundPlayer.outputNode, 'same output node');
133 |
134 |
135 | // now at DECAY_DURATION, we should meet a new player as the old one is taken/stopped
136 | audioContext.$processTo(audioEngine.DECAY_DURATION);
137 |
138 | t.equal(soundPlayer.isStarting, false, 'player.isStarting now false');
139 |
140 | soundPlayer.play();
141 | t.notEqual(originalNode, soundPlayer.outputNode, 'New output node');
142 |
143 | t.end();
144 | });
145 |
146 | });
147 |
148 | suite.test('play while playing', t => {
149 | t.plan(15);
150 | const log = [];
151 | soundPlayer.play();
152 | soundPlayer.finished().then(() => log.push('play 1 finished'));
153 | soundPlayer.connect(audioEngine);
154 | const firstPlayNode = soundPlayer.outputNode;
155 |
156 | // go past debounce time and play again
157 | audioContext.$processTo(audioEngine.DECAY_DURATION);
158 |
159 | return Promise.resolve()
160 | .then(() => {
161 |
162 | t.equal(soundPlayer.outputNode.$state, 'PLAYING');
163 |
164 | soundPlayer.play();
165 | soundPlayer.finished().then(() => log.push('play 2 finished'));
166 |
167 | // wait for a micro-task loop to fire our previous events
168 | return Promise.resolve();
169 | })
170 | .then(() => {
171 |
172 | t.equal(log[0], 'play 1 finished');
173 | t.notEqual(soundPlayer.outputNode, firstPlayNode, 'created new player node');
174 |
175 | t.equal(help.engineInputs.length, 2, 'there should be 2 players connected');
176 | t.equal(firstPlayNode.$state, 'PLAYING');
177 | t.equal(soundPlayer.outputNode.$state, 'PLAYING');
178 | t.equal(help.engineInputs[0].gain.value, 1, 'old sound connectect to gain node with volume 1');
179 |
180 | const {currentTime} = audioContext;
181 | audioContext.$processTo(currentTime + audioEngine.DECAY_WAIT + 0.001);
182 | t.notEqual(help.engineInputs[0].gain.value, 1,
183 | 'old sound connected to gain node which will fade');
184 |
185 | audioContext.$processTo(currentTime + audioEngine.DECAY_WAIT + audioEngine.DECAY_DURATION + 0.001);
186 | t.equal(soundPlayer.outputNode.$state, 'PLAYING');
187 | t.equal(firstPlayNode.$state, 'FINISHED');
188 |
189 | t.equal(help.engineInputs[0].gain.value, 0, 'faded old sound to 0');
190 |
191 | t.equal(log.length, 1);
192 | audioContext.$processTo(currentTime + audioEngine.DECAY_WAIT + audioEngine.DECAY_DURATION + 0.3);
193 |
194 | // wait for a micro-task loop to fire our previous events
195 | return Promise.resolve();
196 | })
197 | .then(() => {
198 |
199 | t.equal(log[1], 'play 2 finished');
200 | t.equal(help.engineInputs.length, 1, 'old sound disconneted itself after done');
201 | t.equal(log.length, 2);
202 |
203 | t.end();
204 | });
205 | });
206 |
207 | suite.end();
208 | });
209 |
--------------------------------------------------------------------------------
/test/__mocks__/AudioContext.js:
--------------------------------------------------------------------------------
1 | const AudioNodeMock = require('./AudioNode');
2 | const AudioParamMock = require('./AudioParam');
3 |
4 | class AudioContextMock {
5 | createGain () {
6 | return new AudioNodeMock({
7 | gain: new AudioParamMock({
8 | default: 1,
9 | min: -3,
10 | max: 3
11 | })
12 | });
13 | }
14 |
15 | createChannelMerger () {
16 | return new AudioNodeMock();
17 | }
18 | }
19 |
20 | module.exports = AudioContextMock;
21 |
--------------------------------------------------------------------------------
/test/__mocks__/AudioEngine.js:
--------------------------------------------------------------------------------
1 | const AudioContextMock = require('./AudioContext');
2 | const AudioTargetMock = require('./AudioTarget');
3 |
4 | class AudioEngineMock extends AudioTargetMock {
5 | constructor () {
6 | super();
7 |
8 | this.audioContext = new AudioContextMock();
9 | }
10 | }
11 |
12 | module.exports = AudioEngineMock;
13 |
--------------------------------------------------------------------------------
/test/__mocks__/AudioNode.js:
--------------------------------------------------------------------------------
1 | class AudioNodeMock {
2 | constructor (params) {
3 | Object.assign(this, params);
4 |
5 | this.connected = null;
6 | this.connectedFrom = [];
7 | this._testResult = [];
8 | }
9 |
10 | connect (node) {
11 | this.connected = node;
12 | node.connectedFrom.push(this);
13 | }
14 |
15 | disconnect () {
16 | if (this.connected !== null) {
17 | this.connectedFrom = this.connectedFrom.filter(connection => connection !== this);
18 | }
19 | this.connected = null;
20 | }
21 |
22 | _test (test, message, depth = 0) {
23 | if (this.connected === null) {
24 | this._testResult.push({test, message, depth});
25 | } else {
26 | this.connected._test(test, message, depth + 1);
27 | this._testResult.push(null);
28 | }
29 | }
30 |
31 | _result () {
32 | return this._testResult.pop();
33 | }
34 | }
35 |
36 | module.exports = AudioNodeMock;
37 |
--------------------------------------------------------------------------------
/test/__mocks__/AudioParam.js:
--------------------------------------------------------------------------------
1 | class AudioParamMock {
2 | setTargetAtTime (value /* , start, stop */) {
3 | this.value = value;
4 | }
5 | setValueAtTime (value) {
6 | this.value = value;
7 | }
8 | linearRampToValueAtTime (value) {
9 | this.value = value;
10 | }
11 | }
12 |
13 | module.exports = AudioParamMock;
14 |
--------------------------------------------------------------------------------
/test/__mocks__/AudioTarget.js:
--------------------------------------------------------------------------------
1 | const AudioNodeMock = require('./AudioNode');
2 |
3 | class AudioTargetMock {
4 | constructor () {
5 | this.inputNode = new AudioNodeMock();
6 | }
7 |
8 | connect (target) {
9 | this.inputNode.connect(target.getInputNode());
10 | }
11 |
12 | getInputNode () {
13 | return this.inputNode;
14 | }
15 |
16 | getSoundPlayers () {
17 | return {};
18 | }
19 | }
20 |
21 | module.exports = AudioTargetMock;
22 |
--------------------------------------------------------------------------------
/test/effects/EffectShape.js:
--------------------------------------------------------------------------------
1 | const tap = require('tap');
2 |
3 | const PanEffect = require('../../src/effects/PanEffect');
4 | const PitchEffect = require('../../src/effects/PitchEffect');
5 | const VolumeEffect = require('../../src/effects/VolumeEffect');
6 |
7 | const AudioEngine = require('../__mocks__/AudioEngine');
8 | const AudioTarget = require('../__mocks__/AudioTarget');
9 |
10 | const testEffect = (EffectClass, effectDepth) => {
11 | tap.test(EffectClass.name, t1 => {
12 | t1.plan(3);
13 |
14 | t1.test('methods', t2 => {
15 | t2.plan(7);
16 |
17 | t2.ok(
18 | 'DEFAULT_VALUE' in EffectClass.prototype,
19 | 'has DEFAULT_VALUE'
20 | );
21 | t2.type(EffectClass.prototype.initialize, 'function', 'has initialize');
22 | t2.type(EffectClass.prototype.set, 'function', 'has set');
23 | t2.type(EffectClass.prototype.update, 'function', 'has update');
24 | t2.type(EffectClass.prototype.clear, 'function', 'has clear');
25 | t2.type(EffectClass.prototype.connect, 'function', 'has connect');
26 | t2.type(EffectClass.prototype.dispose, 'function', 'has dispose');
27 |
28 | t2.end();
29 | });
30 |
31 | t1.test('connect', t2 => {
32 | t2.plan(6);
33 |
34 | const engine = new AudioEngine();
35 | const target = new AudioTarget();
36 | let effect = new EffectClass(engine, target, null);
37 |
38 | target.inputNode._test('stall', 'message does not move');
39 | t2.equal(target.inputNode._result().depth, 0, 'message not sent');
40 | t2.ok(!engine.inputNode._result(), 'message not received');
41 | t2.ok(!engine.inputNode.connected, 'engine not connected');
42 |
43 | effect.dispose();
44 | effect = new EffectClass(engine, target, null);
45 | const effect2 = new EffectClass(engine, target, effect);
46 | effect2.connect(engine);
47 | effect.connect(effect2);
48 |
49 | target.inputNode._test('move', 'message does move');
50 | t2.ok(!target.inputNode._result(), 'message sent');
51 | t2.equal(engine.inputNode._result().depth, 1, 'message received');
52 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
53 |
54 | t2.end();
55 | });
56 |
57 | t1.test('lifecycle', t2 => {
58 | t2.plan(18);
59 |
60 | const engine = new AudioEngine();
61 | const target = new AudioTarget();
62 | let effect = new EffectClass(engine, target, null);
63 | let effect2 = new EffectClass(engine, target, effect);
64 |
65 | target.inputNode._test('stall', 'message does not move');
66 | t2.equal(target.inputNode._result().depth, 0, 'message not sent');
67 | t2.ok(!engine.inputNode._result(), 'message not received');
68 | t2.ok(!engine.inputNode.connected, 'engine not connected');
69 |
70 | effect2.connect(engine);
71 | effect.connect(effect2);
72 |
73 | target.inputNode._test('move', 'message does move');
74 | t2.ok(!target.inputNode._result(), 'message sent');
75 | t2.equal(engine.inputNode._result().depth, 1, 'message received');
76 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
77 |
78 | effect.set(effect.DEFAULT_VALUE - 1);
79 |
80 | target.inputNode._test('move', 'message does move');
81 | t2.ok(!target.inputNode._result(), 'message sent');
82 | t2.equal(engine.inputNode._result().depth, 1 + effectDepth, 'message received');
83 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
84 |
85 | effect2.set(effect2.DEFAULT_VALUE - 1);
86 |
87 | target.inputNode._test('move', 'message does move');
88 | t2.ok(!target.inputNode._result(), 'message sent');
89 | t2.equal(engine.inputNode._result().depth, 1 + (2 * effectDepth), 'message received');
90 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
91 |
92 | effect.clear();
93 |
94 | target.inputNode._test('move', 'message does move');
95 | t2.ok(!target.inputNode._result(), 'message sent');
96 | t2.equal(engine.inputNode._result().depth, 1 + effectDepth, 'message received');
97 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
98 |
99 | effect2.clear();
100 |
101 | target.inputNode._test('move', 'message does move');
102 | t2.ok(!target.inputNode._result(), 'message sent');
103 | t2.equal(engine.inputNode._result().depth, 1, 'message received');
104 | t2.ok(engine.inputNode.connectedFrom.length, 'engine connected');
105 |
106 | t2.end();
107 | });
108 |
109 | t1.end();
110 | });
111 | };
112 |
113 | testEffect(PanEffect, 3);
114 | testEffect(PitchEffect, 0);
115 | testEffect(VolumeEffect, 1);
116 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 |
3 | module.exports = {
4 | mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
5 | devtool: 'cheap-module-source-map',
6 | entry: {
7 | dist: './src/index.js'
8 | },
9 | output: {
10 | path: __dirname,
11 | library: 'AudioEngine',
12 | libraryTarget: 'commonjs2',
13 | filename: '[name].js'
14 | },
15 | module: {
16 | rules: [{
17 | test: /\.js$/,
18 | include: path.resolve(__dirname, 'src'),
19 | loader: 'babel-loader',
20 | options: {
21 | presets: [['env', {targets: {browsers: ['last 3 versions', 'Safari >= 8', 'iOS >= 8']}}]]
22 | }
23 | }]
24 | },
25 | externals: {
26 | 'audio-context': true,
27 | 'minilog': true,
28 | 'startaudiocontext': true
29 | }
30 | };
31 |
--------------------------------------------------------------------------------