· 10 months ago · Nov 14, 2024, 02:11 AM
1-- Find the speaker peripheral
2local speaker = peripheral.find("speaker")
3
4if not speaker then
5 print("No speaker found! Attach a speaker peripheral.")
6 return
7end
8
9-- Key map for the 'W' key
10local W_KEY = keys.w -- ComputerCraft provides this 'keys' API for key codes.
11
12-- Loop to listen for keypresses
13print("Press W to play a note.")
14while true do
15 local event, key = os.pullEvent("key") -- Wait for any keypress event
16
17 if key == W_KEY then
18 -- Play a note with the speaker
19 speaker.playNote("harp", 1, 12) -- Parameters: instrument, volume, pitch
20 print("Played a note!")
21 end
22end
23