Guest User

Untitled

a guest
Oct 21st, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. import synthPresets from './helpers/synth-presets';
  2. import methodPatch from './helpers/method-patch';
  3. import MobileAudioFix from './helpers/mobile-audio-fix';
  4.  
  5. const initialGain = 0.001;
  6.  
  7. export default class Synth {
  8. static synthKeys = Object.keys(synthPresets);
  9.  
  10. constructor() {
  11. this.context = new AudioContext();
  12.  
  13. this.mobileAudio = new MobileAudioFix(this.context);
  14. this.mobileAudio.init();
  15. }
  16.  
  17. play(sound) {
  18. if (!Synth.synthKeys.includes(sound)) {
  19. return Error(`The requested sound is not available: ${sound}`);
  20. }
  21.  
  22. const config = synthPresets[sound];
  23. const duration = this.context.currentTime + config.duration;
  24.  
  25. this._buildTone(config);
  26. // `buildTone` created our `oscillator`,
  27. // so we can now patch both `start()` and `stop()` for Safari
  28. this._patchOscillatorMethods();
  29.  
  30. this.oscillator.start();
  31. this._stop(duration);
  32. }
  33.  
  34. _buildTone(config) {
  35. this.oscillator = this.context.createOscillator();
  36. this.gainNode = this.context.createGain();
  37.  
  38. this.oscillator.connect(this.gainNode);
  39. this.gainNode.connect(this.context.destination);
  40.  
  41. this.oscillator.type = config.wave;
  42. this.oscillator.frequency.setValueAtTime(
  43. config.freq.start,
  44. this.context.currentTime
  45. );
  46. // The oscillator will reach its `end` frequency
  47. // at the half way point of its duration
  48. this.oscillator.frequency.exponentialRampToValueAtTime(
  49. config.freq.end,
  50. this.context.currentTime + (config.duration / 2)
  51. );
  52.  
  53. // We need to do a very quick fade-in
  54. // so we can avoid the ugly "pop" that happens on .start()
  55. this.gainNode.gain.setValueAtTime(
  56. initialGain,
  57. this.context.currentTime
  58. );
  59. this.gainNode.gain.exponentialRampToValueAtTime(
  60. config.volume,
  61. this.context.currentTime + (config.duration / 6)
  62. );
  63. }
  64.  
  65. _stop(duration) {
  66. this.gainNode.gain.exponentialRampToValueAtTime(initialGain, duration);
  67. this.oscillator.stop(duration);
  68. }
  69.  
  70. _patchOscillatorMethods() {
  71. this.oscillator.start = methodPatch.start(this.oscillator);
  72. this.oscillator.stop = methodPatch.stop(this.oscillator);
  73. }
  74. }
Add Comment
Please, Sign In to add comment