Skip to content

Commit

Permalink
quantize note frequency
Browse files Browse the repository at this point in the history
  • Loading branch information
patsimm committed Oct 14, 2024
1 parent 3a65c34 commit a58a0c2
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 7 deletions.
58 changes: 58 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
},
"dependencies": {
"@react-hook/resize-observer": "^2.0.2",
"@tonaljs/note": "^4.11.0",
"classnames": "^2.5.1",
"immer": "^10.1.1",
"react": "^18.3.1",
Expand Down
13 changes: 6 additions & 7 deletions src/synth/SoundNodeState.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
import { Node, State, useAppStore } from "../App.store.ts";
import { Node, useAppStore } from "../App.store.ts";
import { posToTime } from "./bpm.ts";
import { mapObjectValues } from "../helpers.ts";
import { posToFreq } from "./note.ts";

export type SoundNodeState = {
time: number;
length: number;
freq: number;
};

function computeSoundNodeState(node: Node, state: State): SoundNodeState {
function computeSoundNodeState(node: Node): SoundNodeState {
return {
time: posToTime(node.x),
freq: 100 + ((state.size[1] - node.y) / state.size[1]) * 800,
freq: posToFreq(node.y + node.height / 2),
length: posToTime(node.width),
};
}

export function getSoundNodeStates() {
const state = useAppStore.getState();

return mapObjectValues(state.nodes, (node) =>
computeSoundNodeState(node, state),
);
return mapObjectValues(state.nodes, (node) => computeSoundNodeState(node));
}

export function subscribeToNodeState(
Expand All @@ -30,7 +29,7 @@ export function subscribeToNodeState(
) {
useAppStore.subscribe((state, prevState) => {
if (state.nodes[id] !== prevState.nodes[id]) {
cb(computeSoundNodeState(state.nodes[id], state));
cb(computeSoundNodeState(state.nodes[id]));
}
});
}
23 changes: 23 additions & 0 deletions src/synth/note.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Note from "@tonaljs/note";
import { useAppStore } from "../App.store.ts";

const availableNotes = 24;
const base = 60;

export function posToFreq(pos: number) {
const { size } = useAppStore.getState();
const height = size[1];
const noteMidi =
pos === 0
? base - 12
: base -
1 -
12 +
Math.ceil(((height - pos) / height) * (availableNotes + 1));

const freq = Note.freq(Note.fromMidi(noteMidi));
if (freq === null) {
throw new Error("could not determine note frequency!");
}
return freq;
}

0 comments on commit a58a0c2

Please sign in to comment.