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.
92 lines
2.0 KiB
JavaScript
92 lines
2.0 KiB
JavaScript
|
|
const address = document.querySelector('#address').innerHTML
|
|
const socket = new ReconnectingWebSocket(location.origin.replace(/^http/, "ws") + address);
|
|
|
|
|
|
|
|
|
|
const throttle = (fn, delay) => {
|
|
let lastCalled = 0;
|
|
return (...args) => {
|
|
let now = new Date().getTime();
|
|
if (now - lastCalled < delay) {
|
|
return
|
|
}
|
|
lastCalled = now
|
|
return fn(...args)
|
|
}
|
|
}
|
|
|
|
const sendTune = (freq, gain) => {
|
|
socket.send(JSON.stringify({type: 'tune', freq: freq.toFixed(2), gain: gain.toFixed(3)}))
|
|
}
|
|
const sendTuneThrottled = throttle(sendTune,100)
|
|
|
|
|
|
const WIDTH = window.innerWidth
|
|
const HEIGHT = window.innerHeight
|
|
|
|
const canvas = document.querySelector("#draw")
|
|
const canvasContext = canvas.getContext("2d")
|
|
canvas.width = WIDTH
|
|
canvas.height = HEIGHT
|
|
|
|
const audioContext = new AudioContext()
|
|
const oscillator = audioContext.createOscillator()
|
|
const gainNode = audioContext.createGain()
|
|
|
|
|
|
oscillator.connect(gainNode)
|
|
|
|
|
|
const maxFreq = 6000
|
|
const maxVol = 0.2
|
|
const initialVol = 0.001
|
|
|
|
oscillator.start(0)
|
|
oscillator.detune.value = 100
|
|
|
|
oscillator.addEventListener('end', () => {
|
|
console.log("Your tone has stopped")
|
|
})
|
|
|
|
gainNode.gain.value = initialVol
|
|
gainNode.gain.minValue = initialVol
|
|
gainNode.gain.maxValue = initialVol
|
|
|
|
let pressed = false
|
|
let cursorX
|
|
let cursorY
|
|
|
|
|
|
document.addEventListener("mousedown", ()=>{
|
|
pressed = true
|
|
gainNode.connect(audioContext.destination)
|
|
socket.send(JSON.stringify({type: 'start_play'}))
|
|
})
|
|
|
|
document.addEventListener("mouseup", ()=>{
|
|
pressed = false
|
|
gainNode.disconnect(audioContext.destination)
|
|
socket.send(JSON.stringify({type: 'stop_play'}))
|
|
})
|
|
|
|
document.addEventListener("mousemove", (e)=>{
|
|
|
|
cursorX = e.pageX;
|
|
cursorY = e.pageY;
|
|
|
|
let gain = cursorY/HEIGHT*maxVol
|
|
let freq = cursorX/WIDTH*maxFreq
|
|
|
|
gainNode.gain.value = gain;
|
|
oscillator.frequency.value = freq;
|
|
|
|
if (pressed) {
|
|
canvasContext.fillRect(cursorX, cursorY, 5,5)
|
|
canvasContext.fillStyle = "rgb(0,0,0)"
|
|
sendTuneThrottled(freq,gain)
|
|
}
|
|
})
|
|
|