Merge pull request #871 from daslyfe/bugfix_sample_select

bugfix: sound select indexes out of bounds
This commit is contained in:
Felix Roos 2023-12-31 10:06:24 +01:00 committed by GitHub
commit 3760f51c3c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 8 deletions

View file

@ -1,4 +1,4 @@
import { noteToMidi, valueToMidi, nanFallback } from './util.mjs';
import { noteToMidi, valueToMidi, getSoundIndex } from './util.mjs';
import { getAudioContext, registerSound } from './index.mjs';
import { getEnvelope } from './helpers.mjs';
import { logger } from './logger.mjs';
@ -31,10 +31,12 @@ export const getSampleBufferSource = async (s, n, note, speed, freq, bank, resol
transpose = midi - 36; // C3 is middle C
const ac = getAudioContext();
let sampleUrl;
let index = 0;
if (Array.isArray(bank)) {
n = nanFallback(n, 0);
sampleUrl = bank[n % bank.length];
index = getSoundIndex(n, bank.length);
sampleUrl = bank[index];
} else {
const midiDiff = (noteA) => noteToMidi(noteA) - midi;
// object format will expect keys as notes
@ -45,12 +47,13 @@ export const getSampleBufferSource = async (s, n, note, speed, freq, bank, resol
null,
);
transpose = -midiDiff(closest); // semitones to repitch
sampleUrl = bank[closest][n % bank[closest].length];
index = getSoundIndex(n, bank[closest].length);
sampleUrl = bank[closest][index];
}
if (resolveUrl) {
sampleUrl = await resolveUrl(sampleUrl);
}
let buffer = await loadBuffer(sampleUrl, ac, s, n);
let buffer = await loadBuffer(sampleUrl, ac, s, index);
if (speed < 0) {
// should this be cached?
buffer = reverseBuffer(buffer);

View file

@ -61,3 +61,10 @@ export function nanFallback(value, fallback) {
}
return value;
}
// modulo that works with negative numbers e.g. _mod(-1, 3) = 2. Works on numbers (rather than patterns of numbers, as @mod@ from pattern.mjs does)
export const _mod = (n, m) => ((n % m) + m) % m;
// round to nearest int, negative numbers will output a subtracted index
export const getSoundIndex = (n, numSounds) => {
return _mod(Math.round(nanFallback(n, 0)), numSounds);
};