Last active
June 11, 2023 21:17
-
-
Save adactio/d988edc418aabfa2220456dc548dedc1 to your computer and use it in GitHub Desktop.
A function to convert numbers into sound.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 areturn
missing after line 20; alternatively line 22 can be moved into theif
block: