From 7b179546ed644c23cb43f138e520b4b2e55d5a7b Mon Sep 17 00:00:00 2001 From: Eric Rosenbaum Date: Wed, 12 Oct 2016 13:17:51 -0400 Subject: [PATCH] new setup for use with scratch-gui --- src/audio/AudioEngine.js | 163 +++++++++++++++++++++++++++++++++++ src/blocks/scratch3_sound.js | 20 +++-- src/sprites/clone.js | 6 ++ 3 files changed, 180 insertions(+), 9 deletions(-) create mode 100644 src/audio/AudioEngine.js diff --git a/src/audio/AudioEngine.js b/src/audio/AudioEngine.js new file mode 100644 index 000000000..6cbf4c948 --- /dev/null +++ b/src/audio/AudioEngine.js @@ -0,0 +1,163 @@ +var Tone = require('tone'); +var Soundfont = require('soundfont-player'); + +function AudioEngine () { + + // tone setup + + this.tone = new Tone(); + + // effects setup + + this.delay = new Tone.FeedbackDelay(0.25, 0.5); + this.panner = new Tone.Panner(); + this.reverb = new Tone.Freeverb(); + + this.clearEffects(); + + Tone.Master.chain(this.delay, this.panner, this.reverb); + + // drum sounds + + // var drumFileNames = ['high_conga', 'small_cowbell', 'snare_drum', 'splash cymbal']; + // this.drumSamplers = this._loadSoundFiles(drumFileNames); + + // sound urls - map each url to its tone.sampler + this.soundSamplers = []; + + // soundfont setup + + // instrument names used by Musyng Kite soundfont, in order to match scratch instruments + this.instrumentNames = ['acoustic_grand_piano', 'electric_piano_1', 'drawbar_organ', 'acoustic_guitar_nylon', + 'electric_guitar_clean', 'acoustic_bass', 'pizzicato_strings', 'cello', 'trombone', 'clarinet']; + + Soundfont.instrument(Tone.context, this.instrumentNames[0]).then(function (inst) { + this.instrument = inst; + this.instrument.connect(Tone.Master); + }.bind(this)); +} + +AudioEngine.prototype.playSound = function (soundNum) { + this.soundSamplers[soundNum].triggerAttack(); +}; + +AudioEngine.prototype.playSoundFromUrl = function (url) { + if (url) { + // if we've loaded it already, play it + if (this.soundSamplers[url]) { + // this.soundSamplers[url].triggerAttack(); + this.soundSamplers[url].player.start(); + } else { + // else load, play, and store it + // this results in a delay the first time you play the sound + var sampler = new Tone.Sampler(url, function() { + sampler.triggerAttack(); + this.soundSamplers[url] = sampler; + }.bind(this)).toMaster(); + } + } +}; + +AudioEngine.prototype.getSoundDuration = function (url) { + return this.soundSamplers[url].player.buffer.duration; +}; + +AudioEngine.prototype.playNoteForBeats = function(note, beats) { + this.instrument.play(note, Tone.context.currentTime, {duration : Number(beats)}); +}; + +AudioEngine.prototype.playDrumForBeats = function(drumNum, beats) { + this.drumSamplers[drumNum].triggerAttack(); +}; + +AudioEngine.prototype.stopAllSounds = function() { + // stop drum notes + for (var i=0; i