Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active June 11, 2023 21:17
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adactio/d988edc418aabfa2220456dc548dedc1 to your computer and use it in GitHub Desktop.
Save adactio/d988edc418aabfa2220456dc548dedc1 to your computer and use it in GitHub Desktop.
A function to convert numbers into sound.
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
// Pass in an array of numbers ranging from 0 to 20.
function playSparkline(notes) {
if (!window.AudioContext && !window.webkitAudioContext) {
return;
}
var playing = null;
var note = 0;
var output = new (window.AudioContext || window.webkitAudioContext)();
var instrument = output.createOscillator();
var amplifier = output.createGain();
var playNotes = function() {
if (note < notes.length) {
instrument.frequency.value = 440 + (notes[note] * 64); // hertz
note = note + 1;
} else {
amplifier.gain.value = 0;
}
playing = window.setTimeout(playNotes, 25);
};
instrument.type = 'sine'; // 'sine', 'square', 'sawtooth', 'triangle'
instrument.start();
instrument.connect(amplifier);
amplifier.gain.value = 0.7;
amplifier.connect(output.destination);
playNotes();
}
@fran-f
Copy link

fran-f commented Jun 18, 2022

I was exploring the source code of your website, looking for microformats inspiration, when I spotted the code above. The audio API is interesting!

I noticed one thing though: playNotes never stops calling itself, even after the music stops. There's a return missing after line 20; alternatively line 22 can be moved into the if block:

    var playNotes = function() {
        if (note < notes.length) {
            instrument.frequency.value = 440 + (notes[note] * 64); // hertz
            note = note + 1;
            playing = window.setTimeout(playNotes, 25);
        } else {
            amplifier.gain.value = 0;
        }
    };

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