You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
1.9 KiB
Plaintext

// The surface where to tap
const ttt = document.querySelector("#ttt")
// The input to store a sequence
const s = document.querySelector("#s")
let series = []
let initial = null
// The function of a tap
const tap = () => {
if (initial == null) {
initial = new Date()
series.push(0)
} else {
series.push((new Date() - initial))
}
ttt.innerHTML = series
}
const stap = () => {
if (initial == null) return
// insert the final value
series.push((new Date() - initial))
// copy the series
let sequence = series
// reset series and initial date
series = []
initial = null
return sequence
}
const audioContext = new AudioContext()
const gain = new GainNode(audioContext, {
value: 0.05
})
const playNoise = (bandHz=1000, time=0) => {
let noiseDuration = 0.05
const bufferSize = audioContext.sampleRate * noiseDuration
const noiseBuffer = new AudioBuffer({
length: bufferSize,
sampleRate: audioContext.sampleRate
})
const data = noiseBuffer.getChannelData(0)
for (let i=0; i<bufferSize; i++){
data[i] = Math.random() * 2 - 1;
}
const noise = new AudioBufferSourceNode(audioContext, {
buffer: noiseBuffer
})
const bandpass = new BiquadFilterNode(audioContext, {
type: "bandpass",
frequency: bandHz
})
noise.connect(bandpass).connect(gain).connect(audioContext.destination);
noise.start(time)
}
const promiSeq = (sequence) => {
return new Promise((resolve)=>{
const seq = (sequence = []) => {
if (!sequence.length) resolve()
setTimeout( ()=> playNoise(), sequence[0])
sequence.shift()
seq(sequence)
}
seq(sequence)
})
}
ttt.addEventListener("click", () => tap())
s.addEventListener("click", () => {
let sequence = stap();
promiSeq([...sequence])
})