Audio & music

Speaker tune

Plays a short tune on a speaker with note block instruments: a melody, a bass line and drums. Click the emulator to let it play sound.

Likes
0
Views
5
In-game installs
0

Uses

  • speaker

Capabilities

  • Plays audio

Licence

MIT

startup.lua 1945 bytes Raw
1-- A short tune for a speaker, written with note names.
2-- speaker.playNote(instrument, volume, pitch) plays a note block note:
3-- pitch 0 is F#, and every step up is a semitone, up to 24 (two octaves).
4-- Browsers only play sound after you click the page, so click the emulator.
5
6local speaker = peripheral.find("speaker")
7if not speaker then
8 error("Attach a speaker to the computer", 0)
9end
10
11-- Note names to note block pitches. "-" is a rest.
12local PITCH = {
13 ["F#3"] = 0, G3 = 1, A3 = 3, B3 = 5,
14 C4 = 6, D4 = 8, E4 = 10, F4 = 11, G4 = 13, A4 = 15, B4 = 17,
15 C5 = 18, D5 = 20, E5 = 22, ["F#5"] = 24,
16}
17
18-- Each bar is eight steps. The bass sounds two octaves lower than its names.
19local melody = {
20 { "E4", "G4", "C5", "G4", "E5", "D5", "C5", "-" },
21 { "D4", "F4", "A4", "F4", "D5", "C5", "A4", "-" },
22 { "D4", "G4", "B4", "G4", "D5", "C5", "B4", "-" },
23 { "C5", "B4", "A4", "G4", "C5", "-", "E5", "-" },
24}
25local bass = {
26 { "C4", "-", "-", "-", "G4", "-", "-", "-" },
27 { "D4", "-", "-", "-", "A4", "-", "-", "-" },
28 { "G4", "-", "-", "-", "D4", "-", "-", "-" },
29 { "C4", "-", "G4", "-", "C4", "-", "-", "-" },
30}
31-- k: kick (basedrum), s: snare, h: hi-hat
32local drums = { "k", "h", "s", "h", "k", "h", "s", "h" }
33local DRUM = { k = "basedrum", s = "snare", h = "hat" }
34
35local STEP = 0.2 -- seconds per step; the game runs at 20 ticks a second
36
37local function play(instrument, note, volume)
38 if note ~= "-" then
39 speaker.playNote(instrument, volume, PITCH[note])
40 end
41end
42
43for round = 1, 2 do
44 for bar = 1, #melody do
45 print(("Round %d, bar %d"):format(round, bar))
46 for step = 1, 8 do
47 play("harp", melody[bar][step], 1)
48 play("bass", bass[bar][step], 1)
49 speaker.playNote(DRUM[drums[step]], drums[step] == "h" and 0.3 or 0.8, 0)
50 sleep(STEP)
51 end
52 end
53end
54-- And a last chord.
55for _, note in ipairs({ "C4", "E4", "G4", "C5" }) do
56 speaker.playNote("bell", 1, PITCH[note])
57end
58print("Fin.")

Install in your world

wget run https://ccbin.dev/i/EwvlbMwW
wget https://ccbin.dev/raw/EwvlbMwW startup.lua
Embed on your site
<iframe src="https://ccbin.dev/EwvlbMwW/embed" width="800" height="520" style="border:0" loading="lazy" allow="autoplay" title="Speaker tune on ccbin.dev"></iframe>

Sites that understand oEmbed, such as Discord and many forums, make the embed from the program's link.

Plays a short tune on a speaker with note block instruments: a melody, a bass line and drums. Click the emulator to let it play sound.

This is one of the examples in the Workbench. Run it here, or open it in the Workbench to change it.

Comments

No comments yet.

Sign in to comment.