rolling clock average

This commit is contained in:
Jade (Rose) Rowland 2024-08-08 20:55:49 -04:00
parent 7d2110d75f
commit 28334ec94d

View File

@ -2,10 +2,10 @@ import { parseNumeral, Pattern, getEventOffsetMs } from '@strudel/core';
import { Invoke } from './utils.mjs'; import { Invoke } from './utils.mjs';
let offsetTime; let offsetTime;
let weight = 1;
let timeAtPrevOffsetSample; let timeAtPrevOffsetSample;
let rollingOffsetTime; let rollingOffsetTime;
let prevOffsetTimes = []
const averageArray = arr => arr.reduce((a, b) => a + b) / arr.length;
// let prevTime = 0; // let prevTime = 0;
Pattern.prototype.osc = function () { Pattern.prototype.osc = function () {
@ -19,27 +19,27 @@ Pattern.prototype.osc = function () {
controls.note && (controls.note = parseNumeral(controls.note)); controls.note && (controls.note = parseNumeral(controls.note));
const params = []; const params = [];
// console.log(time, currentTime)
const unixTimeSecs = Date.now() / 1000; const unixTimeSecs = Date.now() / 1000;
const newOffsetTime = unixTimeSecs - currentTime; const newOffsetTime = unixTimeSecs - currentTime;
prevOffsetTimes.push(newOffsetTime)
if (unixTimeSecs - timeAtPrevOffsetSample > 2) { if (prevOffsetTimes.length > 8) {
timeAtPrevOffsetSample = unixTimeSecs; prevOffsetTimes.shift()
rollingOffsetTime = newOffsetTime; }
// every two seconds, the average of the previous 8 offset times is calculated
if ( unixTimeSecs - timeAtPrevOffsetSample > 2 || rollingOffsetTime == null) {
timeAtPrevOffsetSample = unixTimeSecs
rollingOffsetTime = averageArray(prevOffsetTimes);
} }
//account for the js clock freezing or resets set the new offset
//account for the js clock freezing or resetting for some reason
if (offsetTime == null || Math.abs(rollingOffsetTime - offsetTime) > .1 if (offsetTime == null || Math.abs(rollingOffsetTime - offsetTime) > .1
) { ) {
offsetTime = newOffsetTime; offsetTime = rollingOffsetTime;
} }
// prevTime = currentTime;
const timestamp = offsetTime + targetTime const timestamp = offsetTime + targetTime
// const timestamp = unixTimeSecs + (targetTime - currentTime)
console.log(offsetTime)
Object.keys(controls).forEach((key) => { Object.keys(controls).forEach((key) => {
const val = controls[key]; const val = controls[key];
const value = typeof val === 'number' ? val.toString() : val; const value = typeof val === 'number' ? val.toString() : val;
@ -62,15 +62,6 @@ Pattern.prototype.osc = function () {
setTimeout(() => { setTimeout(() => {
Invoke('sendosc', { messagesfromjs: [message] }); Invoke('sendosc', { messagesfromjs: [message] });
}); });
// const messagesfromjs = [];
// if (params.length) {
// messagesfromjs.push({ target: '/dirt/play', timestamp, params });
// }
// if (messagesfromjs.length) {
// setTimeout(() => {
// Invoke('sendosc', { messagesfromjs });
// });
// }
}); });
}; };