all files / tests/dummy/app/controllers/ audio-routing.js

12.5% Statements 3/24
0% Branches 0/4
16.67% Functions 1/6
12.5% Lines 3/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80                                                                                                                                                         
import { inject as service } from '@ember/service';
import { on } from '@ember/object/evented';
import Controller from '@ember/controller';
import { Connection } from 'ember-audio';
 
export default Controller.extend({
  audio: service(),
  distortionEnabled: false,
 
  initAudioFile: on('init', function() {
    // Eb5.mp3 is an mp3 file located in the "public" folder
    this.get('audio').load('/ember-audio/Eb5.mp3').asSound('distorted-piano-note').then((note) => {
 
      // Create the connection and insert it into the note's connections array
      note.get('connections').insertAt(1, Connection.create({
        name: 'distortionNode',
        source: 'audioContext',
        createCommand: 'createWaveShaper'
      }));
 
      this.set('note', note);
    });
  }),
 
  _makeDistortionCurve(amount) {
    // I stole this straight from the Mozilla Web Audio API docs site
    const k = typeof amount === 'number' ? amount : 50;
    const numSamples = 44100;
    const curve = new Float32Array(numSamples);
    const deg = Math.PI / 180;
 
    for (let i = 0; i < numSamples; ++i) {
      let x = i * 2 / numSamples - 1;
      curve[i] = (3 + k) * x * 20 * deg / (Math.PI + k * Math.abs(x));
    }
 
    return curve;
  },
 
  _addDistortion() {
    const curve = this._makeDistortionCurve(400);
    const note = this.get('note');
 
    this.set('distortionEnabled', true);
 
    // lower note's gain because distorted signal has much more apparent volume
    note.changeGainTo(0.1).from('ratio');
 
    // Set distortionNode's curve to enable distortion
    note.getNodeFrom('distortionNode').curve = curve;
  },
 
  _removeDistortion() {
    const note = this.get('note');
 
    this.set('distortionEnabled', false);
 
    // raise note's gain because clean signal has much less apparent volume
    note.changeGainTo(1).from('ratio');
 
    // Set distortionNode's curve to null to disable distortion
    note.getNodeFrom('distortionNode').curve = null;
  },
 
  actions: {
    playSound() {
      this.get('note').play();
    },
 
    toggleDistortion() {
      if (this.get('distortionEnabled')) {
        this._removeDistortion();
      } else {
        this._addDistortion();
      }
    }
  }
});