├── .gitignore ├── src ├── icons │ ├── icon-128.png │ ├── icon-144.png │ ├── icon-152.png │ ├── icon-192.png │ ├── icon-256.png │ ├── icon-512.png │ └── icon.svg ├── waveform.ts ├── AudioNode.ts ├── Playback.ts ├── getFrequency.ts ├── manifest.json ├── sw.ts ├── keys.ts ├── Controls.ts ├── audioRecorder.ts ├── createSynthControls.ts ├── Slider.ts ├── midi.ts ├── ToneGenerator.ts ├── AudioTrack.ts ├── index.html ├── style.css └── script.ts ├── tsconfig.json ├── index.d.ts ├── README.md ├── gh-redirect └── index.html ├── test ├── helpers.ts └── e2e │ ├── key-controls.spec.ts │ ├── virtual-keyboard.spec.ts │ └── slider.spec.ts ├── package.json ├── .github └── workflows │ ├── playwright.yml │ └── static.yml ├── esbuild.js ├── playwright.config.ts ├── webmidi.d.ts └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | playwright-report 4 | test-results -------------------------------------------------------------------------------- /src/icons/icon-128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-128.png -------------------------------------------------------------------------------- /src/icons/icon-144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-144.png -------------------------------------------------------------------------------- /src/icons/icon-152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-152.png -------------------------------------------------------------------------------- /src/icons/icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-192.png -------------------------------------------------------------------------------- /src/icons/icon-256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-256.png -------------------------------------------------------------------------------- /src/icons/icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iamschulz/js-synth/HEAD/src/icons/icon-512.png -------------------------------------------------------------------------------- /src/waveform.ts: -------------------------------------------------------------------------------- 1 | export type Waveform = "sine" | "square" | "triangle" | "sawtooth" | "noise"; 2 | -------------------------------------------------------------------------------- /src/AudioNode.ts: -------------------------------------------------------------------------------- 1 | export type MyAudioNode = { 2 | node: OscillatorNode | AudioBufferSourceNode; 3 | release: GainNode; 4 | }; 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "typeRoots": ["index.d.ts"], 4 | "noEmit": true, 5 | "allowImportingTsExtensions": true, 6 | "lib": ["ES2024", "dom"] 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | import { Main } from "./src/script"; 2 | 3 | declare global { 4 | interface Window { 5 | Main: Main; 6 | } 7 | 8 | interface Navigator { 9 | keyboard: { 10 | getLayoutMap: () => Promise<{ 11 | get: (string) => string; 12 | }>; 13 | }; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # js-synth 2 | 3 | a synthesizer PWA written in javascript 4 | 5 | ![](https://jssynth.xyz/icons/icon-256.png) 6 | 7 | - uses the [Web Audio API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API) 8 | - demo: https://jssynth.xyz 9 | 10 | - Build: `npm run build` 11 | - Test: 12 | - `npx playwright install`, `npx playwright install-dependencies` 13 | - `npm run test` 14 | -------------------------------------------------------------------------------- /gh-redirect/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | JSSynth 9 | 10 | 11 | 12 | 13 |

Redirect

14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Playback.ts: -------------------------------------------------------------------------------- 1 | import { RecNote } from "./signalRecorder"; 2 | 3 | export class Playback { 4 | notes: RecNote[]; 5 | ctx: AudioContext; 6 | 7 | constructor(notes: RecNote[]) { 8 | this.notes = notes; 9 | this.ctx = new window.AudioContext(); 10 | } 11 | 12 | public play() { 13 | this.notes.forEach((note) => { 14 | window.setTimeout(() => { 15 | console.log("on", note.key); 16 | }, note.start); 17 | 18 | window.setTimeout(() => { 19 | console.log("off", note.key); 20 | }, note.stop); 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/helpers.ts: -------------------------------------------------------------------------------- 1 | import { Page } from "@playwright/test"; 2 | 3 | export function sleep(time: number): Promise { 4 | return new Promise((resolve) => setTimeout(resolve, time)); 5 | } 6 | 7 | export async function getActiveNotes(page: Page): Promise { 8 | const windowHandle = await page.evaluateHandle(() => window); 9 | const resultHandle = await page.evaluateHandle((window) => window.Main.activeNotes, windowHandle); 10 | const result = await resultHandle.jsonValue(); 11 | await resultHandle.dispose(); 12 | return result; 13 | } 14 | -------------------------------------------------------------------------------- /test/e2e/key-controls.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect } from "@playwright/test"; 2 | import { getActiveNotes, sleep } from "../helpers"; 3 | 4 | test("key controls", async ({ page }) => { 5 | await page.goto("/"); 6 | await sleep(500); 7 | 8 | await page.keyboard.down("KeyQ"); 9 | await expect(await getActiveNotes(page)).toStrictEqual(["c1"]); 10 | 11 | await page.keyboard.down("KeyE"); 12 | await expect(await getActiveNotes(page)).toStrictEqual(["c1", "d1"]); 13 | 14 | await page.keyboard.up("KeyQ"); 15 | await expect(await getActiveNotes(page)).toStrictEqual(["d1"]); 16 | }); 17 | -------------------------------------------------------------------------------- /src/icons/icon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /test/e2e/virtual-keyboard.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect } from "@playwright/test"; 2 | import { getActiveNotes, sleep } from "../helpers"; 3 | 4 | test("virtual-keyboard", async ({ page }) => { 5 | await page.goto("/"); 6 | await sleep(500); 7 | 8 | await page.locator('css=button[data-note="g2"]').dispatchEvent("mousedown"); 9 | await expect(await getActiveNotes(page)).toStrictEqual(["g2"]); 10 | 11 | await page.locator('css=button[data-note="fs2"]').dispatchEvent("mousedown"); 12 | await expect(await getActiveNotes(page)).toStrictEqual(["g2", "fs2"]); 13 | 14 | await page.locator('css=button[data-note="g2"]').dispatchEvent("mouseup"); 15 | await expect(await getActiveNotes(page)).toStrictEqual(["fs2"]); 16 | }); 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "js-synth", 3 | "version": "1.2.2", 4 | "description": "A javascript synthesizer", 5 | "main": "script.js", 6 | "scripts": { 7 | "build": "node ./esbuild.js --minify", 8 | "watch": "node ./esbuild.js --watch", 9 | "test": "playwright test", 10 | "deploy": "npm run build && gh-pages -d dist" 11 | }, 12 | "author": "", 13 | "license": "AGPL-3.0-or-later", 14 | "devDependencies": { 15 | "@playwright/test": "^1.42.1", 16 | "@types/node": "^20.12.2", 17 | "@types/serviceworker": "^0.0.84", 18 | "esbuild": "^0.25.5", 19 | "esbuild-plugin-copy": "^2.1.1", 20 | "gh-pages": "^6.1.1", 21 | "typescript": "^5.4.3" 22 | }, 23 | "dependencies": { 24 | "@fontsource/press-start-2p": "^5.0.19" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/playwright.yml: -------------------------------------------------------------------------------- 1 | name: Playwright Tests 2 | on: 3 | push: 4 | branches: [main, master] 5 | pull_request: 6 | branches: [main, master] 7 | jobs: 8 | test: 9 | timeout-minutes: 60 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-node@v4 14 | with: 15 | node-version: 23 16 | - name: Install dependencies 17 | run: npm ci 18 | - name: Install Playwright Browsers 19 | run: npx playwright install --with-deps 20 | - name: Run Playwright tests 21 | run: npx playwright test 22 | - uses: actions/upload-artifact@v4 23 | if: always() 24 | with: 25 | name: playwright-report 26 | path: playwright-report/ 27 | retention-days: 30 28 | -------------------------------------------------------------------------------- /src/getFrequency.ts: -------------------------------------------------------------------------------- 1 | export function getFrequency(note: string, pitch: number): number { 2 | const semitoneMap: Record = { 3 | c: 0, 4 | cs: 1, 5 | db: 1, 6 | d: 2, 7 | ds: 3, 8 | eb: 3, 9 | e: 4, 10 | f: 5, 11 | fs: 6, 12 | gb: 6, 13 | g: 7, 14 | gs: 8, 15 | ab: 8, 16 | a: 9, 17 | as: 10, 18 | bb: 10, 19 | b: 11, 20 | }; 21 | 22 | const match = note.toLowerCase().match(/^([a-g]{1}s?|[a-g]{1}b?)([-]?\d?)$/); 23 | 24 | if (!match) { 25 | throw new Error("Invalid note name: " + note); 26 | } 27 | 28 | const [, baseNote, octaveStr] = match; 29 | const semitone = semitoneMap[baseNote]; 30 | const octave = octaveStr === "" ? 4 : parseInt(octaveStr); 31 | 32 | const semitonesFromA4 = semitone + (octave - 4) * 12 - 9; 33 | 34 | let freq = +(440 * Math.pow(2, semitonesFromA4 / 12)).toFixed(2); 35 | 36 | for (let i = 0; i <= pitch; i++) { 37 | freq = freq * 2; 38 | } 39 | 40 | return freq; 41 | } 42 | -------------------------------------------------------------------------------- /src/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "JSSynth", 3 | "short_name": "JSSynth", 4 | "icons": [ 5 | { 6 | "src": "icons/icon-128.png", 7 | "sizes": "128x128", 8 | "type": "image/png" 9 | }, 10 | { 11 | "src": "icons/icon-144.png", 12 | "sizes": "144x144", 13 | "type": "image/png" 14 | }, 15 | { 16 | "src": "icons/icon-152.png", 17 | "sizes": "152x152", 18 | "type": "image/png" 19 | }, 20 | { 21 | "src": "icons/icon-192.png", 22 | "sizes": "192x192", 23 | "type": "image/png", 24 | "purpose": "any maskable" 25 | }, 26 | { 27 | "src": "icons/icon-256.png", 28 | "sizes": "256x256", 29 | "type": "image/png" 30 | }, 31 | { 32 | "src": "icons/icon-512.png", 33 | "sizes": "512x512", 34 | "type": "image/png" 35 | } 36 | ], 37 | "lang": "en-US", 38 | "start_url": "./index.html", 39 | "display": "standalone", 40 | "background_color": "DarkSlateGrey", 41 | "theme_color": "DarkSlateGrey" 42 | } 43 | -------------------------------------------------------------------------------- /esbuild.js: -------------------------------------------------------------------------------- 1 | const esbuild = require("esbuild"); 2 | const copyPlugin = require("esbuild-plugin-copy"); 3 | 4 | const watchFlag = process.argv.indexOf("--watch") > -1; 5 | const minifyFlag = process.argv.indexOf("--minify") > -1; 6 | 7 | const opts = { 8 | entryPoints: ["src/script.ts", "src/sw.ts"], 9 | bundle: true, 10 | outdir: "dist", 11 | bundle: true, 12 | minify: minifyFlag, 13 | sourcemap: minifyFlag ? false : "both", 14 | plugins: [ 15 | copyPlugin.copy({ 16 | assets: [ 17 | { from: ["./src/index.html"], to: ["./"] }, 18 | { from: ["./src/style.css"], to: ["./"] }, 19 | { from: ["./src/manifest.json"], to: ["./"] }, 20 | { from: ["./src/icons/*"], to: ["./icons"] }, 21 | { 22 | from: ["./node_modules/@fontsource/press-start-2p/files/press-start-2p-latin-400-normal.woff2"], 23 | to: ["./"], 24 | }, 25 | ], 26 | }), 27 | ], 28 | }; 29 | 30 | if (watchFlag) { 31 | esbuild.context(opts).then(async (ctx) => { 32 | const { port } = await ctx.serve({ 33 | servedir: "dist", 34 | }); 35 | console.log(`Serving on http://127.0.0.1:${port}`); 36 | }); 37 | } else { 38 | esbuild.build(opts); 39 | } 40 | -------------------------------------------------------------------------------- /src/sw.ts: -------------------------------------------------------------------------------- 1 | const ver = "1.2.0"; 2 | const cacheName = `js-synth-${ver}`; 3 | const filesToCache = ["./", "./index.html", "./style.css", "./script.js", "./press-start-2p-latin-400-normal.woff2"]; 4 | const msgChannel = new BroadcastChannel("chan"); 5 | let updateAvailable = false; 6 | 7 | // Start the service worker and cache all of the app's content 8 | self.addEventListener("install", async (e) => { 9 | // check for updates 10 | const keys = await caches.keys(); 11 | keys.forEach((key) => { 12 | if (key !== cacheName) { 13 | updateAvailable = true; 14 | caches.delete(key); 15 | } 16 | }); 17 | 18 | // update notification 19 | if (updateAvailable) { 20 | msgChannel.postMessage({ 21 | type: "update", 22 | version: ver, 23 | }); 24 | } 25 | 26 | updateAvailable = false; 27 | 28 | // cache assets 29 | const cache = await caches.open(cacheName); 30 | await cache.addAll(filesToCache); 31 | }); 32 | 33 | /* Serve cached content when offline */ 34 | self.addEventListener("fetch", function (e) { 35 | e.request.url = e.request.url + (e.request.url.includes("?") ? "&" : "?") + "v=" + ver; 36 | e.respondWith( 37 | caches.open(cacheName).then(function (cache) { 38 | return cache.match(e.request).then(function (response) { 39 | return response || fetch(e.request); 40 | }); 41 | }) 42 | ); 43 | }); 44 | -------------------------------------------------------------------------------- /.github/workflows/static.yml: -------------------------------------------------------------------------------- 1 | # Simple workflow for deploying static content to GitHub Pages 2 | name: Deploy static content to Pages 3 | 4 | on: 5 | # Runs on pushes targeting the default branch 6 | push: 7 | branches: ["main"] 8 | 9 | # Allows you to run this workflow manually from the Actions tab 10 | workflow_dispatch: 11 | 12 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 13 | permissions: 14 | contents: read 15 | pages: write 16 | id-token: write 17 | 18 | # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. 19 | # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. 20 | concurrency: 21 | group: "pages" 22 | cancel-in-progress: false 23 | 24 | jobs: 25 | # Single deploy job since we're just deploying 26 | deploy: 27 | environment: 28 | name: github-pages 29 | url: ${{ steps.deployment.outputs.page_url }} 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Checkout 33 | uses: actions/checkout@v4 34 | - name: Setup Pages 35 | uses: actions/configure-pages@v5 36 | - name: Upload artifact 37 | uses: actions/upload-pages-artifact@v3 38 | with: 39 | # Upload entire repository 40 | path: './gh-redirect' 41 | - name: Deploy to GitHub Pages 42 | id: deployment 43 | uses: actions/deploy-pages@v4 44 | -------------------------------------------------------------------------------- /src/keys.ts: -------------------------------------------------------------------------------- 1 | const baseNotes = ["c", "cs", "d", "eb", "e", "f", "fs", "g", "gs", "a", "bb", "b"]; 2 | 3 | export const keyBindings = [ 4 | "KeyA", 5 | "KeyS", 6 | "KeyD", 7 | "KeyF", 8 | "KeyG", 9 | "KeyH", 10 | "KeyJ", 11 | "KeyK", 12 | "KeyL", 13 | "Semicolon", 14 | "Quote", 15 | "Backslash", 16 | "KeyQ", 17 | "KeyW", 18 | "KeyE", 19 | "KeyR", 20 | "KeyT", 21 | "KeyY", 22 | "KeyU", 23 | "KeyI", 24 | "KeyO", 25 | "KeyP", 26 | "BracketLeft", 27 | "BracketRight", 28 | "Digit1", 29 | "Digit2", 30 | "Digit3", 31 | "Digit4", 32 | "Digit5", 33 | "Digit6", 34 | "Digit7", 35 | "Digit8", 36 | "Digit9", 37 | "Digit0", 38 | "Minus", 39 | "Equal", 40 | ]; 41 | 42 | export const getNote = (input: string | number): string | undefined => { 43 | if (typeof input === "number") { 44 | const octave = Math.floor(input / 12); 45 | const note = baseNotes[input % 12]; 46 | return `${note}${octave}`; 47 | } 48 | 49 | if (typeof input === "string") { 50 | // input is keyCode 51 | const index = keyBindings.indexOf(input); 52 | if (index === -1) { 53 | return undefined; 54 | } 55 | const octave = Math.floor(index / 12); 56 | const note = baseNotes[index % 12]; 57 | return `${note}${octave}`; 58 | } 59 | }; 60 | 61 | export const getMidiCode = (noteName: string) => { 62 | const [note, octave] = noteName.split(""); 63 | const noteIndex = baseNotes.indexOf(note); 64 | if (noteIndex === -1) { 65 | return null; 66 | } 67 | const midiCode = noteIndex + parseInt(octave) * 12; 68 | return midiCode; 69 | }; 70 | 71 | export const getKeyName = (noteName: string) => { 72 | const [note, octave] = noteName.split(""); 73 | const noteIndex = baseNotes.indexOf(note); 74 | if (noteIndex === -1) { 75 | return null; 76 | } 77 | const keyIndex = noteIndex + parseInt(octave) * 12; 78 | if (keyIndex < 0 || keyIndex >= keyBindings.length) { 79 | return null; 80 | } 81 | return keyBindings[keyIndex]; 82 | }; 83 | -------------------------------------------------------------------------------- /playwright.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig, devices } from "@playwright/test"; 2 | 3 | /** 4 | * Read environment variables from file. 5 | * https://github.com/motdotla/dotenv 6 | */ 7 | // require('dotenv').config(); 8 | 9 | /** 10 | * See https://playwright.dev/docs/test-configuration. 11 | */ 12 | export default defineConfig({ 13 | testDir: "./test/e2e", 14 | /* Run tests in files in parallel */ 15 | fullyParallel: false, 16 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 17 | forbidOnly: !!process.env.CI, 18 | /* Retry on CI only */ 19 | retries: process.env.CI ? 3 : 0, 20 | /* Opt out of parallel tests on CI. */ 21 | workers: process.env.CI ? 1 : undefined, 22 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 23 | reporter: process.env.CI ? [["junit", { outputFile: "results_e2e.xml" }]] : "html", 24 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 25 | use: { 26 | /* Base URL to use in actions like `await page.goto('/')`. */ 27 | baseURL: "http://127.0.0.1:8000", 28 | 29 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 30 | trace: "on-first-retry", 31 | }, 32 | 33 | /* Configure projects for major browsers */ 34 | projects: [ 35 | { 36 | name: "chromium", 37 | use: { ...devices["Desktop Chrome"] }, 38 | }, 39 | 40 | { 41 | name: "firefox", 42 | use: { ...devices["Desktop Firefox"] }, 43 | }, 44 | 45 | { 46 | name: "webkit", 47 | use: { ...devices["Desktop Safari"] }, 48 | }, 49 | 50 | /* Test against mobile viewports. */ 51 | { 52 | name: "Mobile Chrome", 53 | use: { ...devices["Pixel 7"] }, 54 | }, 55 | { 56 | name: "Mobile Safari", 57 | use: { ...devices["iPhone 15"] }, 58 | }, 59 | ], 60 | 61 | /* Run your local dev server before starting the tests */ 62 | webServer: { 63 | command: "npm run watch", 64 | url: "http://127.0.0.1:8000", 65 | reuseExistingServer: !process.env.CI, 66 | }, 67 | }); 68 | -------------------------------------------------------------------------------- /src/Controls.ts: -------------------------------------------------------------------------------- 1 | type Attribute = { 2 | name: string; 3 | value: string | number | boolean; 4 | }; 5 | 6 | type Data = { [k: string]: FormDataEntryValue }; 7 | 8 | type Callback = (data: Data) => void; 9 | 10 | export class Controls { 11 | name: string; 12 | el: HTMLFormElement; 13 | attributes: Attribute[]; 14 | callback: Callback; 15 | 16 | constructor(name: string, el: HTMLFormElement, callback: Callback) { 17 | this.name = name; 18 | this.el = el; 19 | this.callback = callback; 20 | 21 | this.attributes = Array.from(el.elements).map((element) => { 22 | const input = element as HTMLInputElement | HTMLSelectElement; 23 | let value: string | number | boolean; 24 | 25 | if (input.type === "range" || input.type === "number") { 26 | value = parseFloat(input.value); 27 | } else if (input.type === "checkbox") { 28 | value = input.checked; 29 | } else { 30 | value = input.value; 31 | } 32 | 33 | return { 34 | name: input.name, 35 | value: value, 36 | } as Attribute; 37 | }); 38 | 39 | this.loadData(); 40 | this.applyData(); 41 | this.persistData(); 42 | 43 | this.el.addEventListener("input", () => { 44 | this.applyData(); 45 | this.persistData(); 46 | }); 47 | } 48 | 49 | loadData(): void { 50 | const str = localStorage.getItem(this.name); 51 | const obj = JSON.parse(str || "{}") as { [k: string]: FormDataEntryValue }; 52 | 53 | this.attributes.forEach((attr) => { 54 | if (obj[attr.name] !== undefined) { 55 | const input = this.el.elements.namedItem(attr.name) as HTMLInputElement | HTMLSelectElement; 56 | if (input) { 57 | if (input.type === "checkbox") { 58 | input.checked = obj[attr.name] === "true"; 59 | } else { 60 | input.value = String(obj[attr.name]); 61 | } 62 | } 63 | } 64 | }); 65 | } 66 | 67 | readData(): Data { 68 | return Object.fromEntries(new FormData(this.el)); 69 | } 70 | 71 | persistData(): void { 72 | localStorage.setItem(this.name, JSON.stringify(this.readData())); 73 | } 74 | 75 | applyData() { 76 | this.callback(this.readData()); 77 | } 78 | 79 | toggleDisable(toggle = true): void { 80 | Array.from(this.el.elements).forEach((element) => { 81 | const input = element as HTMLInputElement | HTMLSelectElement; 82 | input.disabled = toggle; 83 | }); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /test/e2e/slider.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect, Locator } from "@playwright/test"; 2 | import { sleep } from "../helpers"; 3 | 4 | test("slider", async ({ page }) => { 5 | await page.goto("/"); 6 | await sleep(500); 7 | 8 | const countSliderChildren = async () => { 9 | return await page.locator("css=.controls-slider").locator("css=> *").count(); 10 | }; 11 | 12 | const getScrollValue = async (locator: Locator) => { 13 | return await locator.evaluate((el) => { 14 | return el.scrollLeft; 15 | }); 16 | }; 17 | 18 | const slider = await page.locator("css=.controls-slider"); 19 | const addBtn = await page.locator("css=#add-synth"); 20 | const remBtn = await page.locator("css=#remove-synth"); 21 | const prevBtn = await page.locator("css=#prev"); 22 | const nextBtn = await page.locator("css=#next"); 23 | 24 | // default state, 1 synth 25 | await sleep(1000); 26 | await expect(await remBtn.isDisabled()).toBeTruthy(); 27 | await expect(await prevBtn.isDisabled()).toBeTruthy(); 28 | await expect(await nextBtn.isDisabled()).toBeTruthy(); 29 | await expect(await countSliderChildren()).toStrictEqual(1); 30 | await expect(await getScrollValue(slider)).toBe(0); // slider not scrolled 31 | 32 | // add 2nd synth 33 | await addBtn.click(); 34 | await sleep(1000); 35 | await expect(await remBtn.isDisabled()).toBeFalsy(); 36 | await expect(await prevBtn.isDisabled()).toBeFalsy(); 37 | await expect(await nextBtn.isDisabled()).toBeTruthy(); 38 | await expect(await countSliderChildren()).toStrictEqual(2); 39 | await expect(await getScrollValue(slider)).toBeGreaterThan(0); // slider scrolled 40 | 41 | // scroll to 1st synth 42 | await prevBtn.click(); 43 | await sleep(1000); 44 | await expect(await prevBtn.isDisabled()).toBeTruthy(); 45 | await expect(await nextBtn.isDisabled()).toBeFalsy(); 46 | await expect(await getScrollValue(slider)).toBe(0); // slider not scrolled 47 | 48 | // scroll to 2nd synth 49 | await nextBtn.click(); 50 | await sleep(1000); 51 | await expect(await prevBtn.isDisabled()).toBeFalsy(); 52 | await expect(await nextBtn.isDisabled()).toBeTruthy(); 53 | await expect(await getScrollValue(slider)).toBeGreaterThan(0); // slider scrolled 54 | 55 | // remove 2nd synth 56 | await remBtn.click(); 57 | await sleep(1000); 58 | await expect(await remBtn.isDisabled()).toBeTruthy(); 59 | await expect(await prevBtn.isDisabled()).toBeTruthy(); 60 | await expect(await nextBtn.isDisabled()).toBeTruthy(); 61 | await expect(await getScrollValue(slider)).toBe(0); // slider not scrolled 62 | }); 63 | -------------------------------------------------------------------------------- /src/audioRecorder.ts: -------------------------------------------------------------------------------- 1 | import { AudioTrack } from "./AudioTrack"; 2 | 3 | export class AudioRecorder { 4 | ctx: AudioContext; 5 | analyser: AnalyserNode; 6 | recorder: MediaRecorder | null; 7 | singleMode: boolean; 8 | recordingStream: MediaStreamAudioDestinationNode | null; 9 | recordingsList: HTMLUListElement; 10 | recordings: AudioTrack[]; 11 | recordingTemplate: HTMLTemplateElement; 12 | recBtn: HTMLButtonElement; 13 | playBtn: HTMLButtonElement; 14 | 15 | constructor(ctx: AudioContext) { 16 | this.singleMode = true; 17 | 18 | this.ctx = ctx; 19 | this.analyser = this.ctx.createAnalyser(); 20 | 21 | this.recordingTemplate = document.querySelector("#recordingTemplate") as HTMLTemplateElement; 22 | this.recordingsList = document.querySelector("#recordingsList") as HTMLUListElement; 23 | this.recBtn = document.querySelector("#rec") as HTMLButtonElement; 24 | this.playBtn = document.querySelector("#play") as HTMLButtonElement; 25 | 26 | this.recordings = []; 27 | this.recorder = null; 28 | this.recordingStream = null; 29 | 30 | this.recBtn.addEventListener("click", () => { 31 | const active = this.recBtn.ariaPressed === "true"; 32 | if (active) { 33 | this.stopRecording(); 34 | } else { 35 | if (this.singleMode) { 36 | this.recordings.forEach((rec) => rec.audioEl.pause()); 37 | this.recordings = []; 38 | this.recordingsList.querySelectorAll(".audioTrack").forEach((el) => el.remove()); 39 | } 40 | this.startRecording(); 41 | } 42 | this.recBtn.ariaPressed = (!active).toString(); 43 | }); 44 | 45 | this.playBtn.addEventListener("click", () => { 46 | const playing = this.recordings.every((rec) => rec.audioEl.paused === false); 47 | 48 | this.recordings.forEach((rec) => { 49 | if (playing) { 50 | rec.audioEl.pause(); 51 | rec.togglePlay(false); 52 | rec.audioEl.currentTime = 0; 53 | } else { 54 | rec.audioEl.currentTime = 0; 55 | rec.togglePlay(true); 56 | } 57 | }); 58 | 59 | this.playBtn.ariaPressed = (!playing).toString(); 60 | }); 61 | } 62 | 63 | startRecording() { 64 | const audioTrack = new AudioTrack(this.recordings.length); 65 | this.recordings.push(audioTrack); 66 | 67 | this.recorder?.stop(); 68 | this.recordingStream = this.ctx.createMediaStreamDestination(); 69 | this.recorder = new MediaRecorder(this.recordingStream.stream); 70 | this.recorder.start(); 71 | } 72 | 73 | stopRecording() { 74 | this.recorder?.addEventListener("dataavailable", (e) => { 75 | this.recordings.at(-1)?.addSrc(URL.createObjectURL(e.data)); 76 | this.recorder = null; 77 | this.recordingStream = null; 78 | }); 79 | this.recorder?.stop(); 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/createSynthControls.ts: -------------------------------------------------------------------------------- 1 | export const createSynthControls = (i: string): string => ` 2 |
3 |
4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
31 |
32 | 33 | 35 |
36 | 37 |
38 | 39 | 40 |
41 | 42 |
43 | 44 | 46 |
47 | 48 |
49 | 50 | 52 |
53 | 54 |
55 | 56 | 58 |
59 | 60 |
61 | 62 | 64 |
65 | 66 |
67 | 68 | 70 |
71 | 72 |
73 | 74 | 76 |
77 |
78 |
79 | `; 80 | -------------------------------------------------------------------------------- /src/Slider.ts: -------------------------------------------------------------------------------- 1 | export class Slider { 2 | el: HTMLDivElement; 3 | activeItem: HTMLElement; 4 | prevBtn: HTMLButtonElement; 5 | nextBtn: HTMLButtonElement; 6 | changeCallback: (el: HTMLElement) => void; 7 | 8 | constructor(changeCallback: (el: HTMLElement) => void) { 9 | this.el = document.querySelector(".controls-slider")!; 10 | this.prevBtn = document.querySelector("#prev") as HTMLButtonElement; 11 | this.nextBtn = document.querySelector("#next") as HTMLButtonElement; 12 | this.changeCallback = changeCallback; 13 | 14 | this.registerSliderControls(); 15 | this.updateButtons(); 16 | this.restoreSliderPosition(); 17 | 18 | Array.from(this.el.children).forEach((item) => { 19 | this.registerIntersectionObserver(item as HTMLElement); 20 | this.registerFocusEvents(item as HTMLElement); 21 | }); 22 | this.registerMutationObserver(); 23 | } 24 | 25 | registerMutationObserver() { 26 | const options = { childList: true }; 27 | 28 | const callback = (mutationList: MutationRecord[]) => { 29 | for (const mutation of mutationList) { 30 | if (mutation.type !== "childList") { 31 | return; 32 | } 33 | 34 | Array.from(mutation.addedNodes).forEach((item: HTMLElement) => { 35 | this.registerIntersectionObserver(item); 36 | this.registerFocusEvents(item); 37 | }); 38 | } 39 | }; 40 | 41 | const observer = new MutationObserver(callback); 42 | observer.observe(this.el, options); 43 | } 44 | 45 | registerIntersectionObserver(el: HTMLElement) { 46 | const options = { 47 | root: this.el, 48 | rootMargin: "0px", 49 | threshold: 1.0, 50 | }; 51 | 52 | const callback = (items: IntersectionObserverEntry[]) => { 53 | const activeItem = Array.from(items).find((x) => x.isIntersecting)?.target as HTMLElement | null; 54 | if (!activeItem) { 55 | return; 56 | } 57 | this.activeItem = activeItem; 58 | 59 | localStorage.setItem("slider-position", this.el.scrollLeft.toString()); 60 | 61 | window.requestAnimationFrame(() => { 62 | this.updateButtons(); 63 | this.changeCallback(this.activeItem); 64 | }); 65 | }; 66 | 67 | const observer = new IntersectionObserver(callback, options); 68 | observer.observe(el); 69 | } 70 | 71 | restoreSliderPosition(): void { 72 | window.requestAnimationFrame(() => { 73 | this.el.scrollLeft = parseInt(localStorage.getItem("slider-position") || "0"); 74 | }); 75 | } 76 | 77 | registerSliderControls(): void { 78 | this.prevBtn.addEventListener("click", () => { 79 | this.animateScrollSliderToTarget(this.activeItem.previousSibling as HTMLElement); 80 | }); 81 | this.nextBtn.addEventListener("click", () => { 82 | this.animateScrollSliderToTarget(this.activeItem.nextSibling as HTMLElement); 83 | }); 84 | } 85 | 86 | updateButtons(): void { 87 | const isLeft = this.el.scrollLeft <= 50; 88 | const isRight = this.el.scrollLeft + this.el.clientWidth >= this.el.scrollWidth - 50; 89 | this.prevBtn.disabled = isLeft; 90 | this.nextBtn.disabled = isRight; 91 | } 92 | 93 | registerFocusEvents(el: HTMLElement): void { 94 | el.querySelectorAll("input, label").forEach((input) => { 95 | input.addEventListener("focus", () => { 96 | this.animateScrollSliderToTarget(el, true); 97 | }); 98 | }); 99 | } 100 | 101 | animateScrollSliderToTarget(el: HTMLElement, immediate = false): void { 102 | this.el.style.scrollSnapType = "none"; // Disable scroll snapping for smooth animation 103 | 104 | const itemWidth = el.clientWidth; 105 | const position = el.offsetLeft - this.el.offsetLeft + itemWidth / 2 - this.el.clientWidth / 2; // Center the target element in the slider 106 | const start = this.el.scrollLeft; 107 | const distance = position - start; 108 | const duration = immediate ? 1 : 500; // duration in milliseconds 109 | const startTime = performance.now(); 110 | const animateScroll = (currentTime: number) => { 111 | const elapsed = currentTime - startTime; 112 | const progress = Math.min(elapsed / duration, 1); // Ensure progress does not exceed 1 113 | const easeInOutQuad = (t: number) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t); // Easing function 114 | 115 | this.el.scrollLeft = start + distance * easeInOutQuad(progress); 116 | 117 | if (progress < 1) { 118 | window.requestAnimationFrame(animateScroll); 119 | } else { 120 | this.el.style.scrollSnapType = "x mandatory"; // Re-enable scroll snapping after animation 121 | } 122 | }; 123 | 124 | window.requestAnimationFrame(animateScroll); 125 | } 126 | } 127 | -------------------------------------------------------------------------------- /src/midi.ts: -------------------------------------------------------------------------------- 1 | import { Controls } from "./Controls.ts"; 2 | import { getMidiCode } from "./keys.ts"; 3 | 4 | type MidiMessage = { 5 | command: number; 6 | channel: number; 7 | note: number; 8 | velocity: number; 9 | }; 10 | 11 | type Callback = (note: number, velocity?: number) => void; 12 | 13 | type MidiConfig = { 14 | playCallback: Callback; 15 | releaseCallback: Callback; 16 | pitchCallback: Callback; 17 | sustainCallback: Callback; 18 | }; 19 | 20 | export class MidiAdapter { 21 | midi: MIDIAccess | null; 22 | inChannel: number; 23 | outChannel: number; 24 | playCallback: Callback; 25 | releaseCallback: Callback; 26 | pitchCallback: Callback; 27 | sustainCallback: Callback; 28 | disabled: boolean; 29 | activeNotes: number; 30 | controls: Controls; 31 | 32 | constructor(config: MidiConfig) { 33 | this.midi = null; 34 | this.controls = new Controls( 35 | "midiConfig", 36 | document.querySelector("#midi-controls") as HTMLFormElement, 37 | (data) => { 38 | this.inChannel = parseInt(data["midiIn"] as string); 39 | this.outChannel = parseInt(data["midiOut"] as string); 40 | this.checkRequirements(); 41 | } 42 | ); 43 | 44 | this.playCallback = config.playCallback; 45 | this.releaseCallback = config.releaseCallback; 46 | this.pitchCallback = config.pitchCallback; 47 | this.sustainCallback = config.sustainCallback; 48 | 49 | this.disabled = false; 50 | 51 | this.inChannel >= 0 && this.outChannel >= 0 && this.checkRequirements(); 52 | 53 | this.activeNotes = 0; 54 | } 55 | 56 | /** 57 | * Checks if browser meets requirements and grants permissions 58 | * 59 | * @returns 60 | */ 61 | checkRequirements(): void { 62 | if (!navigator.requestMIDIAccess) { 63 | this.disableMidi(); 64 | console.warn("MIDI not supported in this browser."); 65 | return; 66 | } 67 | 68 | if ( 69 | (this.inChannel < 0 || this.inChannel === undefined) && 70 | (this.outChannel < 0 || this.outChannel === undefined) 71 | ) { 72 | return; 73 | } 74 | 75 | navigator 76 | .requestMIDIAccess() 77 | .then(this.onMIDISuccess.bind(this)) 78 | .catch((e) => { 79 | console.error("MIDI access failed:", e); 80 | this.disableMidi(); 81 | }); 82 | } 83 | 84 | /** 85 | * Initializes the MIDI adapter. 86 | * 87 | * @param midiAccess - The granted MIDI access. 88 | */ 89 | onMIDISuccess(midiAccess: MIDIAccess): void { 90 | console.log("MIDI access granted."); 91 | this.midi = midiAccess; 92 | 93 | midiAccess.outputs.forEach((output) => { 94 | console.log( 95 | `Output port [type:'${output.type}'] id:'${output.id}' manufacturer:'${output.manufacturer}' name:'${output.name}' version:'${output.version}'` 96 | ); 97 | }); 98 | 99 | this.watchMidiInput(); 100 | } 101 | 102 | /** 103 | * Callback for MIDI-out from in-browser inputs. 104 | * 105 | * @param key - The key, e.g. 'c2'. 106 | * @param velocity - The velocity of the key. 107 | */ 108 | public onPlayNote(key: string, velocity: number): void { 109 | this.sendMidiMessage("play", key, velocity); 110 | 111 | if (velocity === 0) { 112 | this.activeNotes--; 113 | } else { 114 | this.activeNotes++; 115 | } 116 | } 117 | 118 | /** 119 | * Handles MIDI-in. 120 | */ 121 | watchMidiInput(): void { 122 | this.midi!.inputs.forEach((inputDevice) => { 123 | inputDevice.onmidimessage = (x) => this.onMIDIMessage(x); 124 | }); 125 | } 126 | 127 | /** 128 | * Translates a MIDI-in signal into a readable JSON object. 129 | * 130 | * @param message - The MIDI-in signal 131 | * @returns - The MIDI signal object. 132 | */ 133 | parseMidiMessage(message: string): MidiMessage { 134 | const arr = message.split(" "); 135 | return { 136 | command: parseInt(arr[0]) >> 4, 137 | channel: parseInt(arr[0]) & 0xf, 138 | note: parseInt(arr[1]), 139 | velocity: parseInt(arr[2]) / 127, 140 | }; 141 | } 142 | 143 | /** 144 | * Callback for MIDI input. 145 | * 146 | * @param event - The MIDI event. 147 | * @returns 148 | */ 149 | onMIDIMessage(event): void { 150 | // todo: type event 151 | let str = ""; 152 | for (const character of event.data) { 153 | str += `0x${character.toString(16)} `; 154 | } 155 | str = str.trim(); 156 | if (str === "0xfe") { 157 | return; 158 | } 159 | const data = this.parseMidiMessage(str); 160 | 161 | if (data.channel === this.inChannel && data.command === 9 && data.velocity > 0) { 162 | this.playCallback(data.note, data.velocity); 163 | } 164 | 165 | if ( 166 | (data.channel === this.inChannel && data.command === 8) || 167 | (data.channel === this.inChannel && data.command === 9 && data.velocity === 0) 168 | ) { 169 | this.releaseCallback(data.note); 170 | } 171 | 172 | if (data.channel === this.inChannel && data.command === 8) { 173 | this.releaseCallback(data.note); 174 | } 175 | 176 | if (data.channel === this.inChannel && data.command === 14) { 177 | this.pitchCallback(data.velocity); 178 | } 179 | 180 | if (data.channel === this.inChannel && data.command === 11) { 181 | this.sustainCallback(data.velocity); 182 | } 183 | } 184 | 185 | /** 186 | * Sends out a MIDI message. 187 | * 188 | * @param command - The MIDI command. 189 | * @param note - The MIDI note. 190 | * @param velocity - The velocity. 191 | * @returns 192 | */ 193 | sendMidiMessage(command: string, note: string, velocity = 0): void { 194 | if (this.outChannel < 0 || command !== "play" || !this.midi) { 195 | return; 196 | } 197 | 198 | const midiCode = getMidiCode(note) as any; // todo: fix typing 199 | const midiCommand = "0x" + ((9 << 4) | this.outChannel).toString(16); 200 | const midiVelocity = "0x" + (velocity * 127).toString(16); 201 | 202 | this.midi!.outputs.forEach((outputDevice) => { 203 | outputDevice.send([midiCommand, midiCode, midiVelocity]); 204 | }); 205 | } 206 | 207 | /** 208 | * Disables MIDI option UI. 209 | */ 210 | disableMidi(): void { 211 | this.disabled = true; 212 | window.requestAnimationFrame(() => { 213 | this.controls.toggleDisable(); 214 | }); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /webmidi.d.ts: -------------------------------------------------------------------------------- 1 | interface Navigator { 2 | /** 3 | * When invoked, returns a Promise object representing a request for access to MIDI devices on the 4 | * user's system. 5 | */ 6 | requestMIDIAccess(options?: WebMidiApi.MIDIOptions): Promise; 7 | } 8 | 9 | declare namespace WebMidiApi { 10 | interface MIDIOptions { 11 | /** 12 | * This member informs the system whether the ability to send and receive system 13 | * exclusive messages is requested or allowed on a given MIDIAccess object. 14 | */ 15 | sysex: boolean; 16 | } 17 | 18 | /** 19 | * This is a maplike interface whose value is a MIDIInput instance and key is its 20 | * ID. 21 | */ 22 | type MIDIInputMap = Map; 23 | 24 | /** 25 | * This is a maplike interface whose value is a MIDIOutput instance and key is its 26 | * ID. 27 | */ 28 | type MIDIOutputMap = Map; 29 | 30 | interface MIDIAccess extends EventTarget { 31 | /** 32 | * The MIDI input ports available to the system. 33 | */ 34 | inputs: MIDIInputMap; 35 | 36 | /** 37 | * The MIDI output ports available to the system. 38 | */ 39 | outputs: MIDIOutputMap; 40 | 41 | /** 42 | * The handler called when a new port is connected or an existing port changes the 43 | * state attribute. 44 | */ 45 | onstatechange(e: MIDIConnectionEvent): void; 46 | 47 | addEventListener( 48 | type: "statechange", 49 | listener: (this: this, e: MIDIConnectionEvent) => any, 50 | options?: boolean | AddEventListenerOptions 51 | ): void; 52 | addEventListener( 53 | type: string, 54 | listener: EventListenerOrEventListenerObject, 55 | options?: boolean | AddEventListenerOptions 56 | ): void; 57 | 58 | /** 59 | * This attribute informs the user whether system exclusive support is enabled on 60 | * this MIDIAccess. 61 | */ 62 | sysexEnabled: boolean; 63 | } 64 | 65 | type MIDIPortType = "input" | "output"; 66 | 67 | type MIDIPortDeviceState = "disconnected" | "connected"; 68 | 69 | type MIDIPortConnectionState = "open" | "closed" | "pending"; 70 | 71 | interface MIDIPort extends EventTarget { 72 | /** 73 | * A unique ID of the port. This can be used by developers to remember ports the 74 | * user has chosen for their application. 75 | */ 76 | id: string; 77 | 78 | /** 79 | * The manufacturer of the port. 80 | */ 81 | manufacturer?: string | undefined; 82 | 83 | /** 84 | * The system name of the port. 85 | */ 86 | name?: string | undefined; 87 | 88 | /** 89 | * A descriptor property to distinguish whether the port is an input or an output 90 | * port. 91 | */ 92 | type: MIDIPortType; 93 | 94 | /** 95 | * The version of the port. 96 | */ 97 | version?: string | undefined; 98 | 99 | /** 100 | * The state of the device. 101 | */ 102 | state: MIDIPortDeviceState; 103 | 104 | /** 105 | * The state of the connection to the device. 106 | */ 107 | connection: MIDIPortConnectionState; 108 | 109 | /** 110 | * The handler called when an existing port changes its state or connection 111 | * attributes. 112 | */ 113 | onstatechange(e: MIDIConnectionEvent): void; 114 | 115 | addEventListener( 116 | type: "statechange", 117 | listener: (this: this, e: MIDIConnectionEvent) => any, 118 | options?: boolean | AddEventListenerOptions 119 | ): void; 120 | addEventListener( 121 | type: string, 122 | listener: EventListenerOrEventListenerObject, 123 | options?: boolean | AddEventListenerOptions 124 | ): void; 125 | 126 | /** 127 | * Makes the MIDI device corresponding to the MIDIPort explicitly available. Note 128 | * that this call is NOT required in order to use the MIDIPort - calling send() on 129 | * a MIDIOutput or attaching a MIDIMessageEvent handler on a MIDIInputPort will 130 | * cause an implicit open(). 131 | * 132 | * When invoked, this method returns a Promise object representing a request for 133 | * access to the given MIDI port on the user's system. 134 | */ 135 | open(): Promise; 136 | 137 | /** 138 | * Makes the MIDI device corresponding to the MIDIPort 139 | * explicitly unavailable (subsequently changing the state from "open" to 140 | * "connected"). Note that successful invocation of this method will result in MIDI 141 | * messages no longer being delivered to MIDIMessageEvent handlers on a 142 | * MIDIInputPort (although setting a new handler will cause an implicit open()). 143 | * 144 | * When invoked, this method returns a Promise object representing a request for 145 | * access to the given MIDI port on the user's system. When the port has been 146 | * closed (and therefore, in exclusive access systems, the port is available to 147 | * other applications), the vended Promise is resolved. If the port is 148 | * disconnected, the Promise is rejected. 149 | */ 150 | close(): Promise; 151 | } 152 | 153 | interface MIDIInput extends MIDIPort { 154 | type: "input"; 155 | onmidimessage(e: MIDIMessageEvent): void; 156 | 157 | addEventListener( 158 | type: "midimessage", 159 | listener: (this: this, e: MIDIMessageEvent) => any, 160 | options?: boolean | AddEventListenerOptions 161 | ): void; 162 | addEventListener( 163 | type: "statechange", 164 | listener: (this: this, e: MIDIConnectionEvent) => any, 165 | options?: boolean | AddEventListenerOptions 166 | ): void; 167 | addEventListener( 168 | type: string, 169 | listener: EventListenerOrEventListenerObject, 170 | options?: boolean | AddEventListenerOptions 171 | ): void; 172 | } 173 | 174 | interface MIDIOutput extends MIDIPort { 175 | type: "output"; 176 | 177 | /** 178 | * Enqueues the message to be sent to the corresponding MIDI port. 179 | * @param data The data to be enqueued, with each sequence entry representing a single byte of data. 180 | * @param timestamp The time at which to begin sending the data to the port. If timestamp is set 181 | * to zero (or another time in the past), the data is to be sent as soon as 182 | * possible. 183 | */ 184 | send(data: number[] | Uint8Array, timestamp?: number): void; 185 | 186 | /** 187 | * Clears any pending send data that has not yet been sent from the MIDIOutput 's 188 | * queue. The implementation will need to ensure the MIDI stream is left in a good 189 | * state, so if the output port is in the middle of a sysex message, a sysex 190 | * termination byte (0xf7) should be sent. 191 | */ 192 | clear(): void; 193 | } 194 | 195 | interface MIDIMessageEvent extends Event { 196 | /** 197 | * A timestamp specifying when the event occurred. 198 | */ 199 | receivedTime: number; 200 | 201 | /** 202 | * A Uint8Array containing the MIDI data bytes of a single MIDI message. 203 | */ 204 | data: Uint8Array; 205 | } 206 | 207 | interface MIDIMessageEventInit extends EventInit { 208 | /** 209 | * A timestamp specifying when the event occurred. 210 | */ 211 | receivedTime: number; 212 | 213 | /** 214 | * A Uint8Array containing the MIDI data bytes of a single MIDI message. 215 | */ 216 | data: Uint8Array; 217 | } 218 | 219 | interface MIDIConnectionEvent extends Event { 220 | /** 221 | * The port that has been connected or disconnected. 222 | */ 223 | port: MIDIPort; 224 | } 225 | 226 | interface MIDIConnectionEventInit extends EventInit { 227 | /** 228 | * The port that has been connected or disconnected. 229 | */ 230 | port: MIDIPort; 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /src/ToneGenerator.ts: -------------------------------------------------------------------------------- 1 | import { AudioRecorder } from "./audioRecorder"; 2 | import { Waveform } from "./waveform.ts"; 3 | import { getFrequency } from "./getFrequency.ts"; 4 | import { MyAudioNode } from "./AudioNode.ts"; 5 | import { createSynthControls } from "./createSynthControls.ts"; 6 | import { Controls } from "./Controls.ts"; 7 | 8 | export class ToneGenerator { 9 | id: string; 10 | ctx: AudioContext; 11 | audioRecorder: AudioRecorder; 12 | volume: number; 13 | wave: Waveform; 14 | pitch: number; 15 | threshold: number; 16 | attack: number; 17 | decay: number; 18 | sustain: number; 19 | release: number; 20 | distort: number; 21 | overdrive: number; 22 | nodes: { [key: string]: MyAudioNode }; 23 | controls: Controls; 24 | headerDiagram: SVGElement; 25 | 26 | constructor(id: string, audioRecorder: AudioRecorder, ctx: AudioContext, headerDiagram: SVGElement) { 27 | this.id = id; 28 | this.ctx = ctx; 29 | this.audioRecorder = audioRecorder; 30 | this.volume = 100; 31 | this.wave = "sine"; 32 | this.pitch = 0; 33 | this.threshold = 0.001; 34 | this.attack = 0; 35 | this.decay = 0; 36 | this.sustain = 50; 37 | this.release = 0; 38 | this.distort = 0; 39 | this.overdrive = 0; 40 | this.nodes = {}; 41 | this.headerDiagram = headerDiagram; 42 | this.controls = this.createControls(); 43 | } 44 | 45 | makeDistortionCurve() { 46 | const k = typeof this.distort === "number" ? this.distort : 50; 47 | const n_samples = 44100; 48 | const curve = new Float32Array(n_samples); 49 | const deg = Math.PI / 180; 50 | 51 | for (let i = 0; i < n_samples; i++) { 52 | const x = (i * 2) / n_samples - 1; 53 | curve[i] = ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x)); 54 | } 55 | return curve; 56 | } 57 | 58 | makeOverdriveCurve() { 59 | const k = typeof this.overdrive === "number" ? this.overdrive : 3; 60 | const n_samples = 44100; 61 | const curve = new Float32Array(n_samples); 62 | const deg = Math.PI / 180; 63 | 64 | for (let i = 0; i < n_samples; i++) { 65 | const x = (i * 2) / n_samples - 1; 66 | curve[i] = ((3 + k) * x * 20 * deg) / (Math.PI + k * Math.abs(x)); 67 | } 68 | 69 | for (let i = 0; i < n_samples; i++) { 70 | const x = (i * 2) / n_samples - 1; 71 | if (x < 0) { 72 | curve[i] = Math.tanh(k * x); 73 | } else { 74 | curve[i] = Math.tanh((k * x) / 2); 75 | } 76 | } 77 | 78 | return curve; 79 | } 80 | 81 | /** 82 | * Called when a note starts playing 83 | * 84 | * @param {String} key 85 | */ 86 | playNote(key = "a", velocity = 1, pitchBend = 0.5): void { 87 | const vel = this.ctx.createGain(); 88 | const volume = this.ctx.createGain(); 89 | const release = this.ctx.createGain(); 90 | const freq = getFrequency(key, this.pitch); 91 | const attack = this.ctx.createGain(); 92 | const decay = this.ctx.createGain(); 93 | let distortion: WaveShaperNode | undefined; 94 | let overdriveAmp: WaveShaperNode | undefined; 95 | 96 | let node: AudioBufferSourceNode | OscillatorNode; 97 | 98 | if (["sine", "triangle", "square", "sawtooth"].includes(this.wave)) { 99 | // todo: own function 100 | const osc = this.ctx.createOscillator(); 101 | osc.type = this.wave as OscillatorType; 102 | osc.connect(attack); 103 | osc.frequency.value = freq; 104 | 105 | node = osc; 106 | } else if (this.wave === "noise") { 107 | // todo: own function 108 | const bufSize = this.ctx.sampleRate * 10; 109 | const buf = new AudioBuffer({ 110 | length: bufSize, 111 | sampleRate: this.ctx.sampleRate, 112 | }); 113 | 114 | const data = buf.getChannelData(0); 115 | for (let i = 0; i < bufSize; i++) { 116 | data[i] = Math.random() * 2 - 1; 117 | } 118 | 119 | const noise = new AudioBufferSourceNode(this.ctx, { 120 | buffer: buf, 121 | }); 122 | 123 | const bandpass = new BiquadFilterNode(this.ctx, { 124 | type: "bandpass", 125 | frequency: freq, 126 | }); 127 | 128 | noise.connect(bandpass).connect(attack); 129 | 130 | node = noise; 131 | } else { 132 | return; 133 | } 134 | 135 | /* configure attack */ 136 | attack.gain.setValueAtTime(0.00001, this.ctx.currentTime); 137 | if (this.attack > this.threshold) { 138 | attack.gain.exponentialRampToValueAtTime(0.9, this.ctx.currentTime + this.threshold + this.attack); 139 | } else { 140 | attack.gain.exponentialRampToValueAtTime(0.9, this.ctx.currentTime + this.threshold); 141 | } 142 | 143 | /* configure decay */ 144 | decay.gain.setValueAtTime(1, this.ctx.currentTime + this.attack); 145 | decay.gain.exponentialRampToValueAtTime( 146 | Math.max(this.sustain / 100, 0.000001), 147 | this.ctx.currentTime + this.attack + this.decay 148 | ); 149 | 150 | /* apply distortion */ 151 | if (this.distort > 0) { 152 | distortion = this.ctx.createWaveShaper(); 153 | distortion.curve = this.makeDistortionCurve(); 154 | distortion.oversample = "2x"; 155 | } 156 | 157 | if (this.overdrive > 0) { 158 | overdriveAmp = this.ctx.createWaveShaper(); 159 | overdriveAmp.curve = this.makeOverdriveCurve(); 160 | overdriveAmp.oversample = "2x"; 161 | } 162 | 163 | /* apply key velocity */ 164 | vel.gain.value = vel.gain.value * velocity; 165 | 166 | /* applay master volume */ 167 | volume.gain.value = volume.gain.value * (this.volume / 100); 168 | 169 | /* configure release */ 170 | attack.connect(decay); 171 | decay.connect(vel); 172 | vel.connect(distortion || overdriveAmp || release); 173 | distortion?.connect(overdriveAmp || release); 174 | overdriveAmp?.connect(release); 175 | release.connect(volume); 176 | volume.connect(this.ctx.destination); 177 | 178 | if (this.audioRecorder.recordingStream) { 179 | volume.connect(this.audioRecorder.recordingStream); 180 | } 181 | 182 | /* apply pre-existing pitch bend */ 183 | if (node instanceof OscillatorNode) { 184 | node.frequency.setValueAtTime(freq * (0.5 + pitchBend), this.ctx.currentTime); 185 | } 186 | 187 | this.nodes[key] = { 188 | node: node, 189 | release: release, 190 | }; 191 | 192 | node.start(0); 193 | } 194 | 195 | releaseNote(key: string): void { 196 | const node = this.nodes[key]; 197 | if (!node) { 198 | return; 199 | } 200 | 201 | const release = node.release; 202 | /* configure release */ 203 | release.gain.setValueAtTime(0.9, this.ctx.currentTime); 204 | release.gain.exponentialRampToValueAtTime( 205 | 0.00001, 206 | this.ctx.currentTime + Math.max(this.release, this.threshold) 207 | ); 208 | 209 | // clean up 210 | window.setTimeout(() => { 211 | node.node.stop(this.ctx.currentTime + Math.max(this.release, this.threshold)); 212 | release.disconnect(); 213 | }, (this.release + this.threshold) * 1000); 214 | 215 | Object.keys(this.nodes).forEach((key) => { 216 | if (this.nodes[key] === node) { 217 | delete this.nodes[key]; 218 | } 219 | }); 220 | } 221 | 222 | pitchBend(offset: number): void { 223 | Object.keys(this.nodes).forEach((note) => { 224 | if (this.nodes[note].node instanceof AudioBufferSourceNode) { 225 | // cannot change frequency of AudioBufferSourceNode 226 | return; 227 | } 228 | const node = this.nodes[note].node as OscillatorNode; 229 | 230 | if (offset < 0 || offset > 1) { 231 | throw new Error("Pitch offset must be between 0 and 1"); 232 | } 233 | 234 | const baseFreq = getFrequency(note, this.pitch); 235 | 236 | node.frequency.setValueAtTime(baseFreq * (0.5 + offset), this.ctx.currentTime); 237 | }); 238 | } 239 | 240 | createControls(): Controls { 241 | const html = createSynthControls(this.id); 242 | 243 | // create dom node from html string 244 | const parser = new DOMParser(); 245 | const doc = parser.parseFromString(html, "text/html"); 246 | const el = doc.querySelector(`#synth-controls-${this.id}`) as HTMLFormElement; 247 | 248 | // append controls to DOM 249 | document.querySelector(".controls-slider")?.appendChild(el); 250 | 251 | const controls = new Controls(`synth-controls-${this.id}`, el, (data) => { 252 | this.volume = parseFloat(data[`volume-${this.id}`] as string); 253 | this.wave = data[`waveform-${this.id}`] as Waveform; 254 | this.pitch = parseFloat(data[`pitch-${this.id}`] as string); 255 | this.attack = parseFloat(data[`attack-${this.id}`] as string); 256 | this.decay = parseFloat(data[`decay-${this.id}`] as string); 257 | this.sustain = parseFloat(data[`sustain-${this.id}`] as string); 258 | this.release = parseFloat(data[`release-${this.id}`] as string); 259 | this.distort = parseFloat(data[`distort-${this.id}`] as string); 260 | this.overdrive = parseFloat(data[`overdrive-${this.id}`] as string); 261 | 262 | this.drawAdsr(); 263 | }); 264 | 265 | return controls; 266 | } 267 | 268 | /** 269 | * Draws the ADSR diagram. 270 | */ 271 | drawAdsr(): void { 272 | // todo: animate programmatic changes 273 | 274 | // Draws the waveform. 275 | const waveDiagrams = this.headerDiagram.querySelectorAll('[id^="wave"]'); 276 | waveDiagrams.forEach((waveDiagram) => { 277 | waveDiagram.toggleAttribute("hidden", waveDiagram.id !== `wave-${this.wave}`); 278 | }); 279 | 280 | // header diagram is 400 x 200 281 | const a = this.headerDiagram.querySelector("#adsr-a")!; 282 | const d = this.headerDiagram.querySelector("#adsr-d")!; 283 | const s = this.headerDiagram.querySelector("#adsr-s")!; 284 | const r = this.headerDiagram.querySelector("#adsr-r")!; 285 | 286 | const ax = this.attack * 50 - 0.0; 287 | const dx = (this.decay - 0.0) * 20 + ax; 288 | const sy = 200 - this.sustain * 2; 289 | const rx = 400 - this.release * 10 + 0.0; 290 | 291 | a.toggleAttribute("hidden", ax === 0); 292 | a.setAttribute("x2", ax.toString()); 293 | 294 | d.toggleAttribute("hidden", dx === 0); 295 | d.setAttribute("x1", ax.toString()); 296 | d.setAttribute("x2", dx.toString()); 297 | d.setAttribute("y2", sy.toString()); 298 | 299 | s.setAttribute("x1", dx.toString()); 300 | s.setAttribute("y1", sy.toString()); 301 | s.setAttribute("x2", rx.toString()); 302 | s.setAttribute("y2", sy.toString()); 303 | 304 | r.toggleAttribute("hidden", rx === 400); 305 | r.setAttribute("x1", rx.toString()); 306 | r.setAttribute("y1", sy.toString()); 307 | } 308 | 309 | destroy(): void { 310 | Object.keys(this.nodes).forEach((key) => { 311 | const node = this.nodes[key]; 312 | if (node.node instanceof AudioBufferSourceNode) { 313 | node.node.stop(); 314 | } else if (node.node instanceof OscillatorNode) { 315 | node.node.stop(); 316 | } 317 | node.node.stop(this.ctx.currentTime + Math.max(this.release, this.threshold)); 318 | node.release.disconnect(); 319 | node.release.gain.cancelScheduledValues(this.ctx.currentTime); 320 | }); 321 | 322 | this.nodes = {}; 323 | this.controls.el.remove(); 324 | 325 | localStorage.removeItem(`synth-controls-${this.id}`); 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /src/AudioTrack.ts: -------------------------------------------------------------------------------- 1 | export class AudioTrack { 2 | id: number; 3 | src: string | null; 4 | ready: boolean; 5 | recordingsList: HTMLUListElement; 6 | template: HTMLTemplateElement; 7 | element: HTMLElement; 8 | audioEl: HTMLAudioElement; 9 | duration: number; 10 | mute: boolean; 11 | playButton: HTMLButtonElement; 12 | scrubInput: HTMLInputElement; 13 | currentTimeDisplay: HTMLSpanElement; 14 | vis: HTMLCanvasElement; 15 | indicator: HTMLDivElement; 16 | // enableBtn: HTMLButtonElement; 17 | loopBtn: HTMLButtonElement; 18 | inCtrl: HTMLInputElement; 19 | outCtrl: HTMLInputElement; 20 | wait: number; 21 | in: number; 22 | out: number; 23 | delBtn: HTMLButtonElement; 24 | saveBtn: HTMLButtonElement; 25 | 26 | constructor(id: number) { 27 | this.template = document.querySelector("#recordingTemplate") as HTMLTemplateElement; 28 | this.recordingsList = document.querySelector("#recordingsList") as HTMLUListElement; 29 | 30 | this.id = id; 31 | this.src = null; 32 | this.wait = 0; 33 | this.in = 0; 34 | this.out = 0; 35 | this.mute = false; 36 | 37 | this.createNewAudioElement(); 38 | this.handleTimingControls(); 39 | 40 | this.loop(); 41 | 42 | this.delBtn.addEventListener("click", () => { 43 | this.delete(); 44 | }); 45 | 46 | this.saveBtn.addEventListener("click", () => { 47 | this.save(); 48 | }); 49 | } 50 | 51 | addSrc(src: string) { 52 | this.audioEl.src = src; 53 | this.audioEl.load(); 54 | this.getDuration(this.audioEl.src, (d: number) => { 55 | this.duration = parseFloat(d.toFixed(3)); 56 | this.outCtrl.value = this.duration.toString(); 57 | this.out = this.duration; 58 | this.outCtrl.max = this.duration.toString(); 59 | this.drawWaveform(); 60 | this.element.setAttribute("data-ready", "true"); 61 | }); 62 | } 63 | 64 | getDuration(src: string, next: (duration) => void) { 65 | var player = new Audio(src); 66 | player.addEventListener( 67 | "durationchange", 68 | function () { 69 | if (this.duration != Infinity) { 70 | var duration = this.duration; 71 | player.remove(); 72 | next(duration); 73 | } 74 | }, 75 | false 76 | ); 77 | player.load(); 78 | player.currentTime = 24 * 60 * 60; //fake big time 79 | player.volume = 0; 80 | player.play(); 81 | //waiting... 82 | } 83 | 84 | createNewAudioElement() { 85 | const content = this.template.content; 86 | const recordNode = content.firstElementChild!.cloneNode(true) as HTMLElement; 87 | this.recordingsList.appendChild(recordNode); 88 | 89 | this.element = recordNode; 90 | 91 | const audioEl = recordNode.querySelector("audio") as HTMLAudioElement; 92 | audioEl.id = `recording${this.id}`; 93 | this.audioEl = audioEl; 94 | 95 | // this.enableBtn = recordNode.querySelector('[data-audio-ctrl="enabled"]') as HTMLButtonElement; 96 | this.loopBtn = recordNode.querySelector('[data-audio-ctrl="loop"]') as HTMLButtonElement; 97 | this.inCtrl = recordNode.querySelector('[data-audio-ctrl="in"]') as HTMLInputElement; 98 | this.outCtrl = recordNode.querySelector('[data-audio-ctrl="out"]') as HTMLInputElement; 99 | this.delBtn = recordNode.querySelector('[data-audio-ctrl="del"]') as HTMLButtonElement; 100 | this.saveBtn = recordNode.querySelector('[data-audio-ctrl="save"]') as HTMLButtonElement; 101 | this.playButton = recordNode.querySelector(".audioPlay") as HTMLButtonElement; 102 | this.scrubInput = recordNode.querySelector(".audioScrub") as HTMLInputElement; 103 | this.currentTimeDisplay = recordNode.querySelector(".currentTime") as HTMLSpanElement; 104 | this.vis = recordNode.querySelector("canvas") as HTMLCanvasElement; 105 | this.indicator = recordNode.querySelector(".indicator") as HTMLDivElement; 106 | 107 | this.audioEl.loop = true; 108 | this.audioEl.preload = "auto"; 109 | } 110 | 111 | handleTimingControls() { 112 | this.inCtrl.addEventListener("input", () => { 113 | this.setInpoint(parseFloat(this.inCtrl.value)); 114 | }); 115 | 116 | this.outCtrl.addEventListener("input", () => { 117 | this.setOutpoint(parseFloat(this.outCtrl.value)); 118 | }); 119 | 120 | // this.enableBtn.addEventListener("click", () => { 121 | // this.audioEl.muted = !this.audioEl.muted; 122 | // this.enableBtn.ariaPressed = (!this.audioEl.muted).toString(); 123 | // }); 124 | 125 | this.loopBtn.addEventListener("click", () => { 126 | this.audioEl.loop = !this.audioEl.loop; 127 | this.loopBtn.ariaPressed = this.audioEl.loop.toString(); 128 | }); 129 | 130 | // Event listeners 131 | this.playButton.addEventListener("click", () => this.togglePlay()); 132 | this.scrubInput.addEventListener("input", () => this.scrubAudio()); 133 | this.audioEl.addEventListener("play", () => { 134 | this.updateCurrentTime(); 135 | }); 136 | this.audioEl.addEventListener("pause", () => { 137 | this.playButton.ariaPressed = "false"; 138 | }); 139 | this.audioEl.addEventListener("seeking", () => { 140 | if (this.audioEl.paused) { 141 | return; 142 | } 143 | if (this.audioEl.currentTime > this.out) { 144 | this.audioEl.currentTime = this.out; 145 | } 146 | if (this.audioEl.currentTime < this.in) { 147 | this.audioEl.currentTime = this.in; 148 | } 149 | }); 150 | this.updateCurrentTime(); 151 | } 152 | 153 | setInpoint(time: number) { 154 | this.in = time; 155 | const cssPerc = `${(time / this.duration) * 100}%`; 156 | this.indicator.style.setProperty("--in-pos", cssPerc); 157 | if (this.inCtrl.value !== this.in.toFixed(3)) { 158 | this.inCtrl.value = this.in.toFixed(3); 159 | } 160 | } 161 | 162 | setOutpoint(time: number) { 163 | this.out = time; 164 | const cssPerc = `${(time / this.duration) * 100}%`; 165 | this.indicator.style.setProperty("--out-pos", cssPerc); 166 | if (this.outCtrl.value !== this.out.toFixed(3)) { 167 | this.outCtrl.value = this.out.toFixed(3); 168 | } 169 | } 170 | 171 | loop() { 172 | if (!this.audioEl.paused) { 173 | if (this.audioEl.currentTime <= this.in) { 174 | this.audioEl.currentTime = this.in; 175 | } 176 | if (this.audioEl.currentTime >= this.out) { 177 | this.audioEl.currentTime = this.in; 178 | if (!this.audioEl.loop) { 179 | this.audioEl.pause(); 180 | } 181 | } 182 | } 183 | 184 | window.setTimeout(() => { 185 | this.loop(); 186 | }, 0); 187 | } 188 | 189 | togglePlay(force?: boolean): void { 190 | const play = () => { 191 | this.audioEl.play(); 192 | this.playButton.ariaPressed = "true"; 193 | }; 194 | 195 | const pause = () => { 196 | this.audioEl.pause(); 197 | this.playButton.ariaPressed = "false"; 198 | }; 199 | 200 | if (force === true) { 201 | play(); 202 | } else if (force === false) { 203 | pause(); 204 | } else if (this.audioEl.paused) { 205 | play(); 206 | } else { 207 | pause(); 208 | } 209 | } 210 | 211 | private scrubAudio(): void { 212 | const scrubTime = (parseFloat(this.scrubInput.value) / 10000) * this.duration; 213 | this.audioEl.currentTime = scrubTime; 214 | this.updateCurrentTime(); 215 | } 216 | 217 | private updateCurrentTime(): void { 218 | this.scrubInput.value = String((this.audioEl.currentTime / this.duration) * 10000); 219 | 220 | const inPerc = (this.in / this.duration) * 10000; 221 | const outPerc = (this.out / this.duration) * 10000; 222 | const value = Math.min(Math.max(parseFloat(this.scrubInput.value), inPerc), outPerc) / 100; 223 | this.indicator.style.setProperty("--play-pos", `${value || 0}%`); 224 | this.currentTimeDisplay.textContent = this.formatTime(this.audioEl.currentTime); 225 | 226 | window.requestAnimationFrame(() => { 227 | this.updateCurrentTime(); 228 | }); 229 | } 230 | 231 | private formatTime(seconds: number): string { 232 | const minutes = Math.floor(seconds / 60); 233 | const secs = Math.floor(seconds % 60); 234 | const millis = Math.floor((seconds % 1) * 1000); 235 | return `${minutes < 10 ? "0" : ""}${minutes}:${secs < 10 ? "0" : ""}${secs}:${ 236 | millis < 10 ? "00" : millis < 100 ? "0" : "" 237 | }${millis}`; 238 | } 239 | 240 | async drawWaveform(): Promise { 241 | const audioContext = new window.AudioContext(); 242 | const canvasContext = this.vis.getContext("2d"); 243 | 244 | if (!canvasContext) { 245 | console.error("Failed to get canvas context."); 246 | return; 247 | } 248 | 249 | const response = await fetch(this.audioEl.src); 250 | const arrayBuffer = await response.arrayBuffer(); 251 | const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); 252 | 253 | const channelData = audioBuffer.getChannelData(0); // Use the first channel (mono) 254 | const canvasWidth = this.vis.width; 255 | const canvasHeight = this.vis.height; 256 | 257 | // Calculate the step size to match the canvas width 258 | const step = Math.floor(channelData.length / canvasWidth); 259 | const amplitude = canvasHeight / 2; 260 | 261 | // Clear the canvas before drawing 262 | canvasContext.clearRect(0, 0, canvasWidth, canvasHeight); 263 | canvasContext.fillStyle = "rgba(0,0,0,0)"; // Background color 264 | canvasContext.fillRect(0, 0, canvasWidth, canvasHeight); 265 | canvasContext.strokeStyle = "#ffffff"; // Waveform color 266 | canvasContext.beginPath(); 267 | canvasContext.moveTo(0, amplitude); 268 | 269 | for (let i = 0; i < canvasWidth; i++) { 270 | const slice = channelData.slice(i * step, (i + 1) * step); 271 | const min = Math.min(...slice); 272 | const max = Math.max(...slice); 273 | 274 | const yMin = amplitude + min * amplitude; 275 | const yMax = amplitude + max * amplitude; 276 | 277 | canvasContext.lineTo(i, yMin); 278 | canvasContext.lineTo(i, yMax); 279 | } 280 | 281 | canvasContext.stroke(); 282 | } 283 | 284 | delete() { 285 | this.element.remove(); 286 | } 287 | 288 | async trimAudio(): Promise { 289 | // Fetch the blob from the audio URL 290 | const response = await fetch(this.audioEl.src); 291 | const audioBlob = await response.blob(); 292 | 293 | // Create an audio context 294 | const audioContext = new AudioContext(); 295 | const arrayBuffer = await audioBlob.arrayBuffer(); 296 | 297 | // Decode the audio data 298 | const audioBuffer = await audioContext.decodeAudioData(arrayBuffer); 299 | 300 | // Calculate start and end points in seconds 301 | const startTime = this.in; 302 | const endTime = this.out; 303 | 304 | // Create a new audio buffer with the trimmed duration 305 | const trimmedDuration = endTime - startTime; 306 | const trimmedAudioBuffer = audioContext.createBuffer( 307 | audioBuffer.numberOfChannels, 308 | audioContext.sampleRate * trimmedDuration, 309 | audioContext.sampleRate 310 | ); 311 | 312 | // Copy the audio data from the original buffer to the trimmed buffer 313 | for (let i = 0; i < audioBuffer.numberOfChannels; i++) { 314 | const channelData = audioBuffer.getChannelData(i); 315 | const trimmedChannelData = trimmedAudioBuffer.getChannelData(i); 316 | trimmedChannelData.set( 317 | channelData.subarray( 318 | Math.floor(startTime * audioContext.sampleRate), 319 | Math.floor(endTime * audioContext.sampleRate) 320 | ) 321 | ); 322 | } 323 | 324 | // Create a MediaRecorder to encode the trimmed buffer to a Blob 325 | const destination = audioContext.createMediaStreamDestination(); 326 | const source = audioContext.createBufferSource(); 327 | source.buffer = trimmedAudioBuffer; 328 | source.connect(destination); 329 | source.start(); 330 | 331 | return new Promise((resolve) => { 332 | const recorder = new MediaRecorder(destination.stream); 333 | const chunks: BlobPart[] = []; 334 | 335 | recorder.ondataavailable = (event) => chunks.push(event.data); 336 | recorder.onstop = () => resolve(new Blob(chunks, { type: "audio/webm" })); 337 | 338 | recorder.start(); 339 | source.onended = () => recorder.stop(); 340 | }); 341 | } 342 | 343 | async save() { 344 | this.saveBtn.setAttribute("aria-busy", "true"); 345 | const blob = await this.trimAudio(); 346 | // Create a URL for the blob 347 | const url = URL.createObjectURL(blob); 348 | 349 | // Create an anchor element to trigger the download 350 | const a = document.createElement("a"); 351 | a.href = url; 352 | a.download = `JSSynth_Track_${this.id + 1}.webm`; 353 | document.body.appendChild(a); 354 | a.click(); 355 | 356 | // Clean up by revoking the URL and removing the anchor element 357 | setTimeout(() => { 358 | document.body.removeChild(a); 359 | URL.revokeObjectURL(url); 360 | this.saveBtn.removeAttribute("aria-busy"); 361 | }, 100); 362 | } 363 | } 364 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | JSSynth 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 |

JSSynth

28 | 30 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 |
43 | 44 | Sorry.
45 | Your Browser can't play sounds with this synth.
46 | Maybe try Chrome or Firefox? 47 |
48 | 49 |
50 |
51 |
52 | 53 |
54 |
55 | 56 | 57 | 58 | 59 |
60 |
61 | 64 | 67 | 70 | 73 | 76 | 79 | 82 | 85 | 88 | 91 | 94 | 97 | 98 | 101 | 104 | 107 | 110 | 113 | 116 | 119 | 122 | 125 | 128 | 131 | 134 | 135 | 138 | 141 | 144 | 147 | 150 | 153 | 156 | 159 | 162 | 165 | 168 | 171 |
172 | 173 |
174 | 175 | 176 |
177 | 178 |
    179 | 245 |
246 | 247 |
248 |
249 |
250 |
251 | 252 | 271 |
272 | 273 |
274 | 275 | 294 |
295 |
296 |
297 | made with <3
298 | 299 | Daniel Schulz
300 | (Code) 301 |
302 |
303 |
304 | 305 | 306 | 307 | 308 | -------------------------------------------------------------------------------- /src/style.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: "Press Start 2P"; 3 | font-style: normal; 4 | font-weight: 400; 5 | font-display: swap; 6 | src: url(press-start-2p-latin-400-normal.woff2) format("woff2"); 7 | unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, 8 | U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD; 9 | } 10 | 11 | @keyframes slide-in-top { 12 | from { 13 | opacity: 0; 14 | transform: translateY(2rem); 15 | } 16 | to { 17 | opacity: 1; 18 | transform: translateX(0); 19 | } 20 | } 21 | 22 | @keyframes enable-slider-item { 23 | 0%, 24 | 10% { 25 | opacity: 0; 26 | pointer-events: none; 27 | } 28 | 40%, 29 | 60% { 30 | opacity: 1; 31 | pointer-events: all; 32 | } 33 | 90%, 34 | 100% { 35 | opacity: 0; 36 | pointer-events: none; 37 | } 38 | } 39 | 40 | :root { 41 | --bg: DarkSlateGrey; 42 | --fg: white; 43 | --accent: SpringGreen; 44 | --ui-width: 43.75rem; /* 700px */ 45 | --octaves: 1; 46 | --slider-width: 100%; 47 | --gap-y: 2rem; 48 | } 49 | 50 | @media (min-width: 86rem) { 51 | :root { 52 | --octaves: 2; 53 | --slider-width: 56%; 54 | } 55 | } 56 | 57 | @media (min-width: 132rem) { 58 | :root { 59 | --octaves: 3; 60 | --slider-width: 50%; 61 | } 62 | } 63 | 64 | * { 65 | box-sizing: border-box; 66 | touch-action: manipulation; 67 | } 68 | 69 | html { 70 | overscroll-behavior: none; 71 | } 72 | 73 | body { 74 | color: var(--fg); 75 | background-color: var(--bg); 76 | accent-color: var(--accent); 77 | font-family: "Press Start 2P", monospace; 78 | line-height: 1.3em; 79 | 80 | &::before { 81 | content: ""; 82 | position: fixed; 83 | top: 0; 84 | left: 0; 85 | right: 0; 86 | bottom: 0; 87 | background-image: linear-gradient(160deg, var(--bg) 30%, var(--accent) 200%); 88 | background-image: linear-gradient(180deg, var(--bg) 0rem, transparent 5rem), 89 | linear-gradient(160deg, var(--bg) 30%, var(--accent) 200%); 90 | z-index: -1; 91 | } 92 | } 93 | 94 | .sr-only { 95 | position: absolute; 96 | width: 1px; 97 | height: 1px; 98 | padding: 0; 99 | margin: -1px; 100 | overflow: hidden; 101 | clip: rect(0, 0, 0, 0); 102 | border: 0; 103 | } 104 | 105 | [hidden] { 106 | display: none; 107 | } 108 | 109 | header { 110 | display: flex; 111 | max-width: var(--ui-width); 112 | justify-content: center; 113 | align-items: center; 114 | gap: 1ch; 115 | margin: 0 auto 24px; 116 | } 117 | 118 | a { 119 | color: var(--fg); 120 | } 121 | 122 | .controls-slider { 123 | max-width: calc(var(--ui-width) * var(--octaves)); 124 | margin: 0 auto; 125 | display: flex; 126 | align-items: flex-start; 127 | gap: 1rem; 128 | overflow-x: scroll; 129 | scroll-snap-type: x mandatory; 130 | transition: width 0.2s ease-out; 131 | 132 | scrollbar-color: var(--fg) transparent; 133 | 134 | &::-webkit-scrollbar-track { 135 | border-radius: 6px; 136 | background-color: transparent; 137 | } 138 | 139 | &::-webkit-scrollbar { 140 | width: 6px; 141 | background-color: transparent; 142 | } 143 | 144 | &::-webkit-scrollbar-thumb { 145 | border-radius: 6px; 146 | background-color: var(--fg); 147 | } 148 | 149 | > * { 150 | flex: 0 0 auto; 151 | scroll-snap-align: center; 152 | 153 | @supports (animation-timeline: --enable-slider-item) { 154 | view-timeline-name: --enable-slider-item; 155 | view-timeline-axis: inline; 156 | animation: linear enable-slider-item both; 157 | animation-timeline: --enable-slider-item; 158 | animation-range: cover; 159 | } 160 | } 161 | } 162 | 163 | .synth-controls { 164 | flex: 1 0 var(--slider-width); 165 | max-width: 100%; 166 | display: flex; 167 | gap: 2rem; 168 | justify-content: center; 169 | transition: opacity 0.7s ease-out; 170 | 171 | &:first-of-type { 172 | padding-left: calc((100% - var(--slider-width)) / 2); 173 | flex-basis: calc((100% - var(--slider-width)) / 2 + var(--slider-width)); 174 | } 175 | 176 | &:last-of-type { 177 | padding-right: calc((100% - var(--slider-width)) / 2); 178 | flex-basis: calc((100% - var(--slider-width)) / 2 + var(--slider-width)); 179 | } 180 | } 181 | 182 | .add-remove-synths { 183 | max-width: calc(var(--ui-width) * var(--octaves)); 184 | margin: 0.5rem auto 2rem; 185 | display: flex; 186 | gap: 1rem; 187 | justify-content: center; 188 | } 189 | 190 | .midi-controls { 191 | max-width: calc(var(--ui-width) * var(--octaves)); 192 | margin: 0 auto; 193 | display: block; 194 | margin-bottom: 1rem; 195 | } 196 | 197 | .midi-controls, 198 | .synth-controls { 199 | .controls-box { 200 | display: inline-flex; 201 | flex-direction: column; 202 | margin-bottom: 0.5rem; 203 | } 204 | 205 | & [type="radio"] { 206 | opacity: 0; 207 | width: 0; 208 | pointer-events: none; 209 | 210 | + label { 211 | display: inline-block; 212 | } 213 | 214 | &:focus + label { 215 | outline: -webkit-focus-ring-color auto 1px; 216 | } 217 | 218 | &:checked + label { 219 | color: var(--accent); 220 | } 221 | } 222 | 223 | & select { 224 | width: 9ch; 225 | font: inherit; 226 | border: none; 227 | color: inherit; 228 | background: var(--bg); 229 | padding: 0.4rem; 230 | 231 | &[disabled] { 232 | opacity: 0.5; 233 | pointer-events: none; 234 | } 235 | } 236 | 237 | & .option { 238 | > label { 239 | display: inline-block; 240 | width: 9ch; 241 | } 242 | } 243 | } 244 | 245 | dialog { 246 | position: absolute; 247 | inset: 2rem; 248 | display: none; 249 | align-items: center; 250 | justify-content: center; 251 | z-index: 10; 252 | animation: slide-in-top 0.4s ease-out; 253 | 254 | &::backdrop { 255 | background: rgba(0, 0, 0, 0.5); 256 | backdrop-filter: blur(5px); 257 | -webkit-backdrop-filter: blur(5px); 258 | } 259 | 260 | &[open] { 261 | display: block; 262 | } 263 | 264 | .buttons { 265 | display: flex; 266 | justify-content: center; 267 | gap: 1rem; 268 | margin-top: 2rem; 269 | } 270 | } 271 | 272 | body:has(dialog[open]) { 273 | overflow: hidden; 274 | } 275 | 276 | .keyboard { 277 | position: relative; 278 | display: flex; 279 | justify-items: stretch; 280 | max-width: calc(var(--ui-width) * var(--octaves)); 281 | margin: auto; 282 | user-select: none; 283 | -webkit-user-select: none !important; 284 | 285 | > button { 286 | display: flex; 287 | justify-content: center; 288 | align-items: flex-end; 289 | padding-bottom: 1rem; 290 | font-family: "Press Start 2P", monospace; 291 | border: 1px solid black; 292 | font-size: 0; 293 | text-transform: uppercase; 294 | user-select: none; 295 | -webkit-user-select: none !important; 296 | 297 | &.white { 298 | flex: 1 0 calc(100% / (12 * var(--octaves))); 299 | max-height: 50vw; 300 | height: 18rem; 301 | background-color: var(--fg); 302 | color: grey; 303 | margin: 0 2px; 304 | 305 | + button.white { 306 | margin-left: -1px; 307 | } 308 | 309 | &:focus-visible:not(.active) { 310 | background: orchid; 311 | outline: none; 312 | } 313 | } 314 | 315 | &.black { 316 | flex: 1 0 calc(100% / (12 * var(--octaves)) * 0.4); 317 | max-height: 30vw; 318 | height: 11rem; 319 | margin-left: calc(100% / (12 * var(--octaves)) * -0.5 - 4px); 320 | margin-right: calc(100% / (12 * var(--octaves)) * -0.5 - 4px); 321 | z-index: 1; 322 | background-color: black; 323 | border-left-color: white; 324 | border-right-color: white; 325 | border-bottom-color: white; 326 | color: darkgrey; 327 | 328 | &:focus:not(.active) { 329 | background: darkorchid; 330 | outline: none; 331 | } 332 | } 333 | 334 | &.active { 335 | background: linear-gradient(160deg, var(--bg) -150%, var(--accent) 100%); 336 | color: var(--bg); 337 | outline: none; 338 | } 339 | } 340 | } 341 | 342 | button:not(:is(.black, .white)) { 343 | appearance: none; 344 | background: white; 345 | font-family: "Press Start 2P", monospace; 346 | border: 2px solid currentColor; 347 | padding: 0.3rem; 348 | cursor: pointer; 349 | 350 | &[aria-pressed="true"] { 351 | background: var(--bg); 352 | color: white; 353 | box-shadow: 0 0 1rem 0 var(--bg); 354 | } 355 | 356 | &:active:not([disabled]) { 357 | background: var(--accent); 358 | color: initial; 359 | } 360 | 361 | &[disabled] { 362 | opacity: 0.5; 363 | cursor: not-allowed; 364 | } 365 | } 366 | 367 | .recordingControls { 368 | display: flex; 369 | align-items: center; 370 | justify-content: center; 371 | gap: 1rem; 372 | margin: var(--gap-y) auto 0.5rem; 373 | max-width: calc(var(--ui-width) * var(--octaves)); 374 | transition: opacity 0.2s ease-out; 375 | 376 | &:not(:has(+ #recordingsList li[data-ready="true"] + li[data-ready="true"])) :where(#play, #save) { 377 | display: none; 378 | opacity: 0; 379 | } 380 | } 381 | 382 | #rec { 383 | border-color: black; 384 | transition: opacity 0.2s ease-out; 385 | 386 | &[aria-pressed="true"] { 387 | background: red; 388 | color: white; 389 | box-shadow: 0 0 1rem 0 red; 390 | } 391 | } 392 | 393 | .recordingControls:has(+ #recordingsList > .audioTrack[data-ready="true"]) { 394 | #rec { 395 | opacity: 0; 396 | pointer-events: none; 397 | } 398 | } 399 | 400 | #recordingsList { 401 | list-style: none; 402 | padding: 0; 403 | display: flex; 404 | flex-direction: column; 405 | gap: 0.5rem; 406 | max-width: calc(var(--ui-width) * var(--octaves)); 407 | margin: auto; 408 | 409 | button { 410 | min-width: 3rem; 411 | min-height: 3rem; 412 | font-size: 1.5rem; 413 | 414 | &:has(svg) { 415 | line-height: 0rem; 416 | } 417 | 418 | svg { 419 | height: 1rem; 420 | } 421 | } 422 | } 423 | 424 | .audioTrack { 425 | display: grid; 426 | grid-template-columns: 7ch auto 3rem 3rem 3rem; 427 | grid-template-rows: 1fr 1fr; 428 | grid-template-areas: 429 | "in out loop del down" 430 | "play audio audio audio audio"; 431 | gap: 0 1rem; 432 | align-items: center; 433 | width: 100%; 434 | opacity: 0; 435 | pointer-events: none; 436 | transition: opacity 0.2s ease-out; 437 | 438 | &[data-ready="true"] { 439 | opacity: 1; 440 | pointer-events: all; 441 | } 442 | 443 | @media (min-width: 86rem) { 444 | grid-template-columns: 7ch 3rem auto 7ch 3rem 3rem 3rem; 445 | grid-template-rows: auto; 446 | grid-template-areas: "in play audio out loop del down"; 447 | gap: 1rem; 448 | } 449 | 450 | audio { 451 | flex: 1 0 auto; 452 | height: 1.8rem; 453 | } 454 | 455 | label { 456 | display: flex; 457 | align-items: center; 458 | } 459 | 460 | input[type="number"] { 461 | width: 7ch; 462 | height: 3rem; 463 | font-family: "Press Start 2P", monospace; 464 | 465 | &[data-audio-ctrl="out"] { 466 | text-align: right; 467 | } 468 | } 469 | 470 | .audioPlay { 471 | grid-area: play; 472 | } 473 | 474 | .vis, 475 | .indicator { 476 | width: 100%; 477 | height: 4rem; 478 | position: absolute; 479 | inset: 0; 480 | pointer-events: none; 481 | } 482 | 483 | .indicator { 484 | --col-out: rgb(from var(--bg) r g b / 0.8); 485 | --col-out: coral; 486 | background: linear-gradient( 487 | 90deg, 488 | transparent var(--in-pos, 0%), 489 | var(--accent) var(--in-pos, 0%), 490 | var(--accent) var(--play-pos, 0%), 491 | transparent var(--play-pos, 0%) 492 | ), 493 | linear-gradient(90deg, var(--col-out) var(--in-pos, 0%), transparent var(--in-pos, 0%)), 494 | linear-gradient(90deg, transparent var(--out-pos, 100%), var(--col-out) var(--out-pos, 100%)); 495 | mix-blend-mode: darken; 496 | } 497 | 498 | .audioPlayer { 499 | grid-area: audio; 500 | position: relative; 501 | flex: 1 1 100%; 502 | 503 | .audioScrub { 504 | width: 100%; 505 | height: 4rem; 506 | opacity: 0; 507 | } 508 | 509 | .currentTime { 510 | position: absolute; 511 | inset: 0.2rem; 512 | display: grid; 513 | place-items: center; 514 | text-shadow: -1px -1px 0 var(--bg), 1px -1px 0 var(--bg), -1px 1px 0 var(--bg), 1px 1px 0 var(--bg); 515 | pointer-events: none; 516 | z-index: 1; 517 | } 518 | } 519 | 520 | [data-audio-ctrl="mute"] { 521 | position: relative; 522 | cursor: pointer; 523 | 524 | input { 525 | position: absolute; 526 | top: -400%; 527 | left: -100%; 528 | transform: rotate(-90deg); 529 | } 530 | } 531 | 532 | [data-audio-ctrl="save"] { 533 | &[data-loading="true"] { 534 | opacity: 0.5; 535 | pointer-events: none; 536 | } 537 | } 538 | } 539 | 540 | footer { 541 | max-width: var(--ui-width); 542 | margin: var(--gap-y) auto 0; 543 | text-align: center; 544 | font-size: 0.75rem; 545 | } 546 | 547 | @media (min-width: 48rem) { 548 | .keyboard { 549 | button { 550 | font-size: 1.2em; 551 | } 552 | } 553 | } 554 | 555 | @media (max-width: 85.999rem) { 556 | .md { 557 | display: none !important; 558 | } 559 | } 560 | 561 | @media (max-width: 131.999rem) { 562 | .lg { 563 | display: none !important; 564 | } 565 | } 566 | -------------------------------------------------------------------------------- /src/script.ts: -------------------------------------------------------------------------------- 1 | import { AudioRecorder } from "./audioRecorder"; 2 | import { MidiAdapter } from "./midi.ts"; 3 | import { getKeyName, getNote } from "./keys.ts"; 4 | import { ToneGenerator } from "./ToneGenerator.ts"; 5 | import { Slider } from "./Slider.ts"; 6 | 7 | export class Main { 8 | ctx: AudioContext; 9 | keys: { 10 | [key: string]: { 11 | key: string; 12 | midiIn: number; 13 | }; 14 | }; 15 | pitchBend: number; 16 | activeNotes: string[]; 17 | pressedKeys: Set; 18 | keyBtns: NodeListOf; 19 | headerDiagram: SVGElement; 20 | MidiAdapter: MidiAdapter; 21 | midiIn: number; 22 | midiOut: number; 23 | AudioRecorder: AudioRecorder; 24 | toneGenerators: ToneGenerator[]; 25 | addBtn: HTMLButtonElement; 26 | removeBtn: HTMLButtonElement; 27 | slider: Slider; 28 | sustain: boolean; 29 | 30 | constructor() { 31 | if (!window.AudioContext) { 32 | (document.querySelector(".error") as HTMLDialogElement).showModal(); 33 | return; 34 | } 35 | 36 | this.ctx = new window.AudioContext(); 37 | this.headerDiagram = document.querySelector("#header-vis")!; 38 | 39 | this.AudioRecorder = new AudioRecorder(this.ctx); 40 | this.toneGenerators = this.loadSavedToneGenerators(); 41 | this.toneGenerators[0].drawAdsr(); 42 | 43 | this.slider = new Slider((el: HTMLElement) => { 44 | const id = el.id.split("-")[2]; 45 | const activeToneGenerator = this.toneGenerators.find((tg) => tg.id === id); 46 | activeToneGenerator?.drawAdsr(); 47 | }); 48 | 49 | this.pitchBend = 0.5; 50 | this.sustain = false; 51 | this.activeNotes = []; 52 | this.pressedKeys = new Set(); 53 | this.keyBtns = document.querySelectorAll(".keyboard button"); 54 | 55 | this.addBtn = document.querySelector("#add-synth") as HTMLButtonElement; 56 | this.addBtn.addEventListener("click", () => { 57 | this.addSynth(); 58 | }); 59 | 60 | this.removeBtn = document.querySelector("#remove-synth") as HTMLButtonElement; 61 | this.removeBtn.addEventListener("click", () => { 62 | this.removeSynth(); 63 | }); 64 | 65 | this.keyboardControls(); 66 | this.buttonControls(); 67 | this.updateLegend(); 68 | 69 | if (this.toneGenerators.length === 1) { 70 | this.removeBtn.disabled = true; // disable remove button if only one synth is left 71 | } 72 | 73 | this.MidiAdapter = new MidiAdapter({ 74 | playCallback: this.onMidiPlay.bind(this), 75 | releaseCallback: this.onMidiRelease.bind(this), 76 | pitchCallback: this.onMidiPitchBend.bind(this), 77 | sustainCallback: this.onMidiSustain.bind(this), 78 | }); 79 | 80 | this.killDeadNodes(); 81 | } 82 | 83 | loadSavedToneGenerators(): ToneGenerator[] { 84 | const items = { ...localStorage }; 85 | const toneGenerators = Object.keys(items) 86 | .filter((key) => key.startsWith("synth-controls-")) 87 | .sort((a, b) => { 88 | const aId = parseInt(a.split("-")[2]); 89 | const bId = parseInt(b.split("-")[2]); 90 | return aId - bId; 91 | }) 92 | .map((key) => { 93 | const id = key.split("-")[2]; 94 | return new ToneGenerator(id, this.AudioRecorder, this.ctx, this.headerDiagram); 95 | }); 96 | 97 | if (toneGenerators.length === 0) { 98 | const tg = new ToneGenerator(Date.now().toString(), this.AudioRecorder, this.ctx, this.headerDiagram); 99 | toneGenerators.push(tg); 100 | } 101 | 102 | return toneGenerators; 103 | } 104 | 105 | addSynth(): void { 106 | const toneGenerator = new ToneGenerator( 107 | Date.now().toString(), 108 | this.AudioRecorder, 109 | this.ctx, 110 | this.headerDiagram 111 | ); 112 | this.toneGenerators.push(toneGenerator); 113 | this.slider.animateScrollSliderToTarget(toneGenerator.controls.el); 114 | 115 | this.removeBtn.disabled = false; // enble remove button when a second synth is added 116 | } 117 | 118 | removeSynth(): void { 119 | if (this.toneGenerators.length <= 1) { 120 | return; // cannot remove the last synth 121 | } 122 | 123 | const activeElement = this.slider.activeItem; 124 | const synthId = activeElement?.id.split("-")[2]; 125 | const activeToneGenerator = this.toneGenerators.find((tg) => tg.id === synthId); 126 | if (!activeToneGenerator) { 127 | return; // no active tone generator to remove 128 | } 129 | 130 | const scrollTarget = (activeToneGenerator.controls.el.nextSibling || 131 | activeToneGenerator.controls.el.previousSibling) as HTMLElement; 132 | this.slider.animateScrollSliderToTarget(scrollTarget); 133 | activeToneGenerator.controls.el.style.opacity = "0"; 134 | 135 | window.setTimeout(() => { 136 | const scrollLeft = this.slider.el.scrollLeft - scrollTarget.clientWidth; 137 | activeToneGenerator.destroy(); 138 | this.toneGenerators = this.toneGenerators.filter((tg) => tg.id !== activeToneGenerator.id); 139 | this.slider.el.scrollLeft = scrollLeft; // prevent scroll jump in safari 140 | 141 | if (this.toneGenerators.length === 1) { 142 | this.removeBtn.disabled = true; // disable remove button if only one synth is left 143 | } 144 | this.slider.updateButtons(); 145 | }, 520); 146 | } 147 | 148 | /** 149 | * Called when a note starts playing 150 | * 151 | * @param {String} key 152 | */ 153 | playNote(key = "a", velocity = 1): void { 154 | if (this.sustain && this.pressedKeys.has(key)) { 155 | this.endNote(key, true); 156 | } 157 | if (this.activeNotes.includes(key)) { 158 | return; // note is already playing 159 | } 160 | 161 | this.toneGenerators.forEach((toneGenerator) => { 162 | toneGenerator.playNote(key, velocity, this.pitchBend); 163 | }); 164 | 165 | Array.from(this.keyBtns) 166 | .filter((btn) => btn.dataset.note === key)[0] 167 | ?.classList.add("active"); 168 | 169 | this.activeNotes.push(key); 170 | 171 | this.MidiAdapter?.onPlayNote(key, velocity); 172 | } 173 | 174 | /** 175 | * Called when a note stops playing 176 | * 177 | * @param {Object} node 178 | */ 179 | endNote(key: string, force = false): void { 180 | if (this.sustain && !force) { 181 | return; 182 | } 183 | 184 | this.toneGenerators.forEach((toneGenerator) => { 185 | toneGenerator.releaseNote(key); 186 | }); 187 | 188 | Array.from(this.keyBtns) 189 | .filter((btn) => btn.dataset.note === key)[0] 190 | ?.classList.remove("active"); 191 | 192 | this.activeNotes = this.activeNotes.filter((note) => note !== key); 193 | 194 | this.MidiAdapter?.onPlayNote(key, 0); 195 | } 196 | 197 | /** 198 | * Listens to keyboard inputs. 199 | */ 200 | keyboardControls(): void { 201 | document.addEventListener("keydown", (e) => { 202 | if (e.repeat) { 203 | return; 204 | } 205 | const recordingsList = document.querySelector("#recordingsList") as HTMLElement; 206 | if (recordingsList.contains(document.activeElement)) { 207 | if (e.code === "KeyI") { 208 | const time = this.AudioRecorder.recordings[0].audioEl.currentTime; 209 | this.AudioRecorder.recordings[0].setInpoint(time); 210 | } 211 | if (e.code === "KeyO") { 212 | const time = this.AudioRecorder.recordings[0].audioEl.currentTime; 213 | this.AudioRecorder.recordings[0].setOutpoint(time); 214 | } 215 | if (e.code === "Space" && (e.target as HTMLElement).classList.contains("audioScrub")) { 216 | e.preventDefault(); 217 | this.AudioRecorder.recordings[0].togglePlay(); 218 | } 219 | } else { 220 | const note = getNote(e.code); 221 | 222 | if (!note) { 223 | return; 224 | } 225 | 226 | this.pressedKeys.add(note); 227 | this.playNote(note); 228 | } 229 | }); 230 | 231 | document.addEventListener("keyup", (e) => { 232 | const note = getNote(e.code); 233 | 234 | if (!note) { 235 | return; 236 | } 237 | this.pressedKeys.delete(note); 238 | 239 | this.endNote(note); 240 | }); 241 | } 242 | 243 | transpose(keyName: string, offset: number): string { 244 | const octave = parseInt(keyName.slice(-1)); 245 | const note = keyName.slice(0, -1); 246 | return `${note}${octave + offset}`; 247 | } 248 | 249 | /** 250 | * Calback for MIDI inputs for key presses. 251 | * 252 | * @param midiCode - Code of the key. 253 | * @param velocity - Velocity of the key. 254 | * 255 | * @returns 256 | */ 257 | onMidiPlay(midiCode: number, velocity: number): void { 258 | let note = getNote(midiCode); 259 | 260 | if (!note) { 261 | return; 262 | } 263 | 264 | note = this.transpose(note, -4); 265 | 266 | if (this.sustain && this.pressedKeys.has(note)) { 267 | this.endNote(note, true); 268 | } 269 | 270 | this.pressedKeys.add(note); 271 | this.playNote(note, velocity); 272 | } 273 | 274 | /** 275 | * Calback for MIDI inputs for key releases. 276 | * 277 | * @param midiCode - Code of the key. 278 | * 279 | * @returns 280 | */ 281 | onMidiRelease(midiCode: number): void { 282 | let note = getNote(midiCode); 283 | 284 | if (!note) { 285 | return; 286 | } 287 | 288 | note = this.transpose(note, -4); 289 | this.pressedKeys.delete(note); 290 | this.endNote(note); 291 | } 292 | 293 | /** 294 | * Callback for MIDI pitch bend inputs. 295 | * 296 | * @param offset - Pitch offset, between 0 and 1, 0.5 is no offset. 297 | */ 298 | onMidiPitchBend(offset: number): void { 299 | this.pitchBend = offset; 300 | this.toneGenerators.forEach((toneGenerator) => { 301 | toneGenerator.pitchBend(offset); 302 | }); 303 | } 304 | 305 | onMidiSustain(toggle: number): void { 306 | this.sustain = !!toggle; 307 | if (!this.sustain) { 308 | this.onSustainEnd(); 309 | } 310 | } 311 | 312 | onSustainEnd(): void { 313 | this.activeNotes.forEach((key) => { 314 | if (!this.pressedKeys.has(key)) { 315 | this.endNote(key); 316 | } 317 | }); 318 | } 319 | 320 | /** 321 | * Handles on-screen button inputs. 322 | */ 323 | buttonControls(): void { 324 | this.keyBtns.forEach((btn) => { 325 | /* click button */ 326 | btn.addEventListener( 327 | "mousedown", 328 | (e) => { 329 | const key = btn.dataset.note; 330 | if (!key) return; 331 | 332 | this.playNote(key); 333 | }, 334 | { passive: true } 335 | ); 336 | 337 | btn.addEventListener( 338 | "touchstart", 339 | (e) => { 340 | const key = btn.dataset.note; 341 | if (!key) return; 342 | 343 | this.playNote(key); 344 | }, 345 | { passive: true } 346 | ); 347 | 348 | /* change button while clicked */ 349 | btn.addEventListener( 350 | "mouseenter", 351 | (e) => { 352 | const key = btn.dataset.note; 353 | if (!e.buttons || !key) return; 354 | 355 | this.playNote(key); 356 | }, 357 | { passive: true } 358 | ); 359 | 360 | /* trigger button with tab controls */ 361 | btn.addEventListener("keypress", (e) => { 362 | if (!(e.code === "Space" || e.key === "Enter")) return; 363 | this.playNote((e.target as HTMLButtonElement).dataset.note); 364 | }); 365 | 366 | /* release button */ 367 | btn.addEventListener( 368 | "mouseup", 369 | (e) => { 370 | const key = btn.dataset.note; 371 | if (!key || !this.activeNotes.includes(key)) return; 372 | 373 | this.endNote(key); 374 | }, 375 | { passive: true } 376 | ); 377 | 378 | btn.addEventListener( 379 | "mouseout", 380 | (e) => { 381 | const key = btn.dataset.note; 382 | if (!key || !this.activeNotes.includes(key)) return; 383 | 384 | this.endNote(key); 385 | }, 386 | { passive: true } 387 | ); 388 | 389 | btn.addEventListener( 390 | "touchend", 391 | (e) => { 392 | const key = btn.dataset.note; 393 | if (!key || !this.activeNotes.includes(key)) return; 394 | 395 | this.endNote(key); 396 | }, 397 | { passive: true } 398 | ); 399 | 400 | btn.addEventListener( 401 | "touchcancel", 402 | (e) => { 403 | const key = btn.dataset.note; 404 | if (!key || !this.activeNotes.includes(key)) return; 405 | 406 | this.endNote(key); 407 | }, 408 | { passive: true } 409 | ); 410 | 411 | btn.addEventListener("keyup", (e) => { 412 | const key = btn.dataset.note; 413 | if (!(e.code === "Space" || e.key === "Enter")) return; 414 | if (!key || !this.activeNotes.includes(key)) return; 415 | 416 | this.endNote(key); 417 | }); 418 | 419 | btn.addEventListener("blur", () => { 420 | const key = btn.dataset.note; 421 | if (!key || !this.activeNotes.includes(key)) return; 422 | 423 | this.endNote(key); 424 | }); 425 | }); 426 | } 427 | 428 | /** 429 | * 430 | * @returns Updates the legend on the on-screen keys according to the users keymap. 431 | */ 432 | async updateLegend(): Promise { 433 | if (!navigator.keyboard?.getLayoutMap) { 434 | return; 435 | } 436 | 437 | const layoutMap = await navigator.keyboard.getLayoutMap(); 438 | this.keyBtns.forEach((btn) => { 439 | const noteName = btn.dataset.note; 440 | const keyName = getKeyName(noteName!); 441 | if (!keyName) return; 442 | btn.textContent = layoutMap.get(keyName) || keyName; 443 | }); 444 | } 445 | 446 | killDeadNodes(): void { 447 | if (this.MidiAdapter?.activeNotes === 0 && !document.querySelector("button.active")) { 448 | Object.keys(this.activeNotes).forEach((note) => { 449 | this.endNote(note); 450 | }); 451 | } 452 | 453 | window.setTimeout(() => { 454 | window.requestAnimationFrame(() => { 455 | this.killDeadNodes(); 456 | }); 457 | }, 100); 458 | } 459 | } 460 | 461 | const swListener = new BroadcastChannel("chan"); 462 | swListener.onmessage = (e) => { 463 | if (e.data && e.data.type === "update") { 464 | if (e.data) { 465 | const dialog = document.createElement("dialog"); 466 | dialog.innerHTML = ` 467 |

468 | Update available!
469 | Please refresh to load version ${e.data.version}. 470 |

471 |
472 | 473 | 474 |
475 | `; 476 | document.body.appendChild(dialog); 477 | dialog.addEventListener("close", () => { 478 | document.body.removeChild(dialog); 479 | }); 480 | const refreshBtn = dialog.querySelector(".refresh") as HTMLButtonElement; 481 | refreshBtn.addEventListener("click", () => { 482 | window.location.reload(); 483 | }); 484 | 485 | const closeBtn = dialog.querySelector(".close") as HTMLButtonElement; 486 | closeBtn?.addEventListener("click", () => { 487 | dialog.close(); 488 | }); 489 | 490 | dialog.showModal(); 491 | } 492 | } 493 | }; 494 | 495 | document.querySelectorAll("dialog").forEach((el) => { 496 | const closeBtn = el.querySelector(".close") as HTMLButtonElement | null; 497 | closeBtn?.addEventListener("click", () => { 498 | el.close(); 499 | }); 500 | }); 501 | 502 | // start synth 503 | window.Main = new Main(); 504 | 505 | // register sw 506 | window.onload = async () => { 507 | "use strict"; 508 | 509 | if ("serviceWorker" in navigator) { 510 | await navigator.serviceWorker.register("./sw.js"); 511 | } 512 | }; 513 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------