Skip to content

Instantly share code, notes, and snippets.

@adactio
Last active Aug 27, 2022
Embed
What would you like to do?
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