Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active June 30, 2026 18:07
Show Gist options
  • Select an option

  • Save luizbills/9a2fef98f27172d23c7c04d7a4a58235 to your computer and use it in GitHub Desktop.

Select an option

Save luizbills/9a2fef98f27172d23c7c04d7a4a58235 to your computer and use it in GitHub Desktop.
extra sound functions for Litecanvas
/**
* @param {number} frequency
* @param {number} [duration] in seconds
* @param {number} [wavetype] 0 (sine), 1 (triangle), 2 (saw), 3 (tan), 4 (noise) or 5 (square)
* @param {number} [volume]
*/
function beep(frequency, duration = 0.1, wavetype = 1, volume = .5) {
sfx([, 0, frequency, 0.01, duration, 0.01, wavetype], 0, volume)
}
/**
* Get frequency of a note on a musical scale
*
* @param {number} semitoneOffset - How many semitones away from the root note
* @param {number} [rootFrequency=220] - Frequency at semitone offset 0
* @returns {number} - The frequency of the note
*/
function notefreq(semitoneOffset, rootFrequency = 220) {
return rootFrequency * (2 ** (semitoneOffset/12));
}
/**
* @param {number[][]} notes
* @param {number} [gap] seconds between each note
*/
function melody(notes, gap = 0.1) {
for (let i = 0; i < notes.length; i++) {
const note = notes[i] || [0]
let t = T + i * gap
const handler = (dt) => {
if (T >= t) {
beep(...note)
unlisten('update', handler)
}
}
listen('update', handler)
}
}

Usage

Play just a note

beep(440, 0.5) // play the frequency 440Hz for 0.5 second

Play a sequence of notes

melody(
    [
        [notefreq(12), 0.1, 0, 0.3], // note=A, dur=0.1, wave=sine, volume=0.3
        [notefreq(14), 0.1, 0, 0.5], // note=B, dur=0.1, wave=sine, volume=0.5
        [notefreq(15), 0.1, 0, 0.6], // note=C, dur=0.1, wave=sine, volume=0.6
    ],
    0.25 // wait 0.25 seconds between each note
)
@luizbills

luizbills commented May 11, 2026

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment