1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
local SONGS = require("songs")
local KEYS = {
Z = 0,
S = 1,
X = 2,
D = 3,
C = 4,
V = 5,
G = 6,
B = 7,
H = 8,
N = 9,
J = 10,
M = 11,
Comma = 12,
L = 13,
Period = 14,
Semicolon = 15,
Slash = 16,
Q = 12,
["2"] = 13,
W = 14,
["3"] = 15,
E = 16,
R = 17,
["5"] = 18,
T = 19,
["6"] = 20,
Y = 21,
["7"] = 22,
U = 23,
I = 24,
["9"] = 25,
O = 26,
["0"] = 27,
P = 28,
LeftBrace = 29,
Equal = 30,
RightBrace = 31,
}
local BASE = 48
local MAX_SHIFT = 1
local FADE_STEP = 15
local HTTP_PORT = 47800
local WS_PORT = 47801
local cfg = UI.Schema({
toggleKey = UI.Keybind("F8", { label = "Piano on or off", tab = "Keys" }),
songKey = UI.Keybind(
"F9",
{ label = "Play or stop the chosen song", tab = "Keys" }
),
sustainKey = UI.Keybind("Space", { label = "Sustain pedal", tab = "Keys" }),
octaveDownKey = UI.Keybind("Left", { label = "Octave down", tab = "Keys" }),
octaveUpKey = UI.Keybind("Right", { label = "Octave up", tab = "Keys" }),
volume = UI.Slider(60, {
min = 10,
max = 100,
step = 5,
suffix = "%",
label = "Note volume",
tab = "Sound",
}),
damperTime = UI.Slider(1800, {
min = 100,
max = 3000,
step = 50,
suffix = " ms",
label = "Damper: how long a released note takes to die away",
tab = "Sound",
}),
lessons = UI.Toggle(true, {
label = `Serve the game page at http://localhost:{HTTP_PORT}`,
tab = "Game",
}),
openPage = UI.Toggle(true, {
label = "Open the game page when the script starts",
tab = "Game",
}),
})
local on = true
local octave = 0
local pedal = false
local held = {}
local sustained = {}
local socket = nil
local function emit(message)
if socket and socket:ClientCount() > 0 then
socket:Broadcast(JSON.Stringify(message))
end
end
local fading = {}
local function damp(sound)
local volume = sound:GetVolume()
fading[sound] = {
volume = volume,
floor = volume / 1000,
ratio = 0.001 ^ (FADE_STEP / cfg.damperTime),
}
end
Timer.Every(FADE_STEP, function()
for sound, fade in fading do
fade.volume *= fade.ratio
if fade.volume <= fade.floor or not sound:IsPlaying() then
sound:Stop()
fading[sound] = nil
else
sound:SetVolume(fade.volume)
end
end
end)
local function dampSustained()
for _, sound in sustained do
damp(sound)
end
sustained = {}
end
local function playing()
if not on then
return false
end
local m = Input.GetModifiers()
return not (m.ctrl or m.alt or m.win)
end
local function play(note, source)
local ok, sound =
pcall(Audio.Play, `samples/{note}.ogg`, { volume = cfg.volume / 100 })
if not ok then
Log.Error(`note {note}: {sound}`)
return nil
end
emit({ t = "down", note = note, src = source })
return sound
end
for key, semitone in KEYS do
Bind(key, {
when = playing,
action = function()
local note = BASE + semitone + 12 * octave
local sound = play(note, "key")
held[key] = if sound then { sound = sound, note = note } else nil
return nil
end,
release = function()
local press = held[key]
held[key] = nil
if press == nil then
return
end
emit({ t = "up", note = press.note, src = "key" })
if pedal then
table.insert(sustained, press.sound)
else
damp(press.sound)
end
end,
})
end
Bind(cfg.sustainKey, {
when = playing,
action = function()
pedal = true
return nil
end,
release = function()
pedal = false
dampSustained()
end,
})
local function shift(by)
octave = math.max(-MAX_SHIFT, math.min(MAX_SHIFT, octave + by))
UI.Notify(`Octave {if octave > 0 then "+" else ""}{octave}`, "info")
emit({ t = "octave", octave = octave })
end
Bind(cfg.octaveDownKey, {
when = playing,
action = function()
shift(-1)
return nil
end,
})
Bind(cfg.octaveUpKey, {
when = playing,
action = function()
shift(1)
return nil
end,
})
local selected = SONGS[#SONGS]
local hands = {}
local ringing = {}
local function songPlaying()
for _, hand in hands do
if hand:IsRunning() then
return true
end
end
return false
end
local function stopSong()
for _, hand in hands do
hand:Cancel()
end
hands = {}
for sound, note in ringing do
emit({ t = "up", note = note, src = "song" })
damp(sound)
end
ringing = {}
end
local function playHand(notes, step)
for i = 1, #notes, 2 do
local note = notes[i]
local sound = if note ~= 0 then play(note, "song") else nil
if sound then
ringing[sound] = note
end
Sleep(notes[i + 1] * step)
if sound then
ringing[sound] = nil
emit({ t = "up", note = note, src = "song" })
damp(sound)
end
end
end
local function startSong(leftOnly, speed)
stopSong()
local song = selected
local step = song.step / speed
hands = {
Run(function()
playHand(song.left, step)
end),
}
if not leftOnly then
table.insert(
hands,
Run(function()
playHand(song.right, step)
end)
)
end
end
Bind(cfg.songKey, {
when = playing,
action = function()
if songPlaying() then
stopSong()
else
startSong(false, 1)
end
return nil
end,
})
local function silence()
stopSong()
Audio.StopAll()
fading = {}
held = {}
sustained = {}
pedal = false
end
Bind(cfg.toggleKey, function()
on = not on
if not on then
silence()
end
UI.Notify(if on then "Piano on" else "Piano off, keys type", "info")
return nil
end)
local function songById(id)
for _, song in SONGS do
if song.id == id then
return song
end
end
return nil
end
local function onPageMessage(_, payload, isBinary)
if isBinary or #payload > 200 then
return
end
local ok, message = pcall(JSON.Parse, payload)
if not ok or type(message) ~= "table" then
return
end
if message.t == "stop" then
stopSong()
return
end
local song = songById(message.id)
if song == nil then
return
end
if message.t == "select" then
stopSong()
selected = song
elseif message.t == "play" and on then
selected = song
local speed = if type(message.speed) == "number" then message.speed else 1
startSong(message.hands == "left", math.max(0.4, math.min(1.5, speed)))
end
end
local function servePage(request)
if request.method ~= "GET" then
return { status = 405, body = "GET only" }
end
if request.path == "/" then
return {
body = File.Read("site/index.html"),
headers = { ["Content-Type"] = "text/html; charset=utf-8" },
}
end
if request.path == "/piano.json" then
return {
body = JSON.Stringify({
keys = KEYS,
base = BASE,
wsPort = WS_PORT,
songs = SONGS,
}),
headers = { ["Content-Type"] = "application/json" },
}
end
return { status = 404, body = "not found" }
end
function OnStart()
Log.Info(
`Z and Q rows play. {cfg.sustainKey} sustains, {cfg.octaveDownKey} and {cfg.octaveUpKey} shift octaves, {cfg.songKey} plays a song, {cfg.toggleKey} turns the piano off so keys type again.`
)
if not cfg.lessons then
return
end
Net.Listen(HTTP_PORT, servePage)
Timer.After(500, function()
socket = Net.WSListen(WS_PORT, {
OnConnect = function(client)
client:Send(JSON.Stringify({
t = "hello",
octave = octave,
selected = selected.id,
}))
end,
OnMessage = onPageMessage,
})
end)
local url = `http://localhost:{HTTP_PORT}`
Log.Info(`Game page: {url}`)
if not cfg.openPage then
return
end
Timer.After(2500, function()
if socket:ClientCount() > 0 then
return
end
local mac = _REBIND.platform == "macos"
local ok, err = pcall(
System.ExecDetached,
if mac then "open" else "rundll32",
if mac then { url } else { "url.dll,FileProtocolHandler", url }
)
if not ok then
Log.Warn(`could not open {url}: {err}`)
end
end)
end
function OnStop()
silence()
end
function OnError(message)
Log.Error(message)
silence()
end