Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions resources/js/lib/voice-notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,23 @@ export function waveformOf(samples: Float32Array, bars = voiceBars): number[] {
*/
export function barsOf(levels: number[], bars = voiceBars): number[] {
return Array.from({ length: bars }, (_, bar) => {
if (levels.length === 0) {
return 0;
}

const from = Math.floor((levels.length * bar) / bars);
const to = Math.max(
from + 1,
Math.floor((levels.length * (bar + 1)) / bars),
);

return Math.round(
Math.min(1, Math.max(0, ...levels.slice(from, to))) * 100,
);
let peak = 0;

for (let index = from; index < to; index++) {
peak = Math.max(peak, levels[index] as number);
}

return Math.round(Math.min(1, peak) * 100);
});
}

Expand Down
20 changes: 20 additions & 0 deletions tests/Unit/VoiceNotes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,23 @@ void test('reads the saved volume as a whole percent, at full volume until a sen
assert.equal(voiceVolumeOf('-0.3'), 0);
assert.equal(voiceVolumeOf('1.5'), 1);
});

void test('samples long voice level sequences without changing peak bars', () => {
const levels = Array(4800).fill(0.1);
levels[2000] = 0.8;
const bars = barsOf(levels);

assert.equal(bars.length, voiceBars);
assert.equal(bars[20], 80);
assert.equal(bars[19], 10);
assert.equal(bars[21], 10);
});

void test('keeps clamping and NaN behavior for voice level bars', () => {
assert.deepEqual(barsOf([-0.5], 1), [0]);
assert.equal(Number.isNaN(barsOf([Number.NaN], 1)[0]), true);

const sparse = Array<number>(2);
sparse[1] = 0.5;
assert.equal(Number.isNaN(barsOf(sparse, 1)[0]), true);
});