All files resonance-audio-room.js

93.94% Statements 62/66
94.44% Branches 34/36
85.71% Functions 6/7
96.67% Lines 58/60

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245  1x 1x   1x         1x   1x                                                     45x 45x 45x     45x 45x     45x     45x 45x     45x 43x         50x 50x 50x 50x                           45x 45x 45x             95x                       95x 95x                     99x 42x                       57x 42x   99x               93x 93x 93x 93x   2x 2x   93x                 11x   7x                 45x       2x                   45x   45x               45x 45x   45x               1x       3x   1x 1x 1x 1x       2x 2x         3x 3x     4x       1x                                        
/* global AFRAME, THREE, AudioContext */
const { ResonanceAudio } = require('resonance-audio')
const { onceWhenLoaded, getBoundingBox } = require('./utils')
 
const RESONANCE_MATERIAL = Object.keys(ResonanceAudio.Utils.ROOM_MATERIAL_COEFFICIENTS)
 
/**
 * The Object3D name of the visualization.
 */
const visName = 'audio-room'
 
AFRAME.registerComponent('resonance-audio-room', {
  dependencies: ['position', 'rotation'],
 
  schema: {
    // Room dimensions. The position is the center point of this box.
    width: { type: 'number', default: ResonanceAudio.Utils.DEFAULT_ROOM_DIMENSIONS.width },
    height: { type: 'number', default: ResonanceAudio.Utils.DEFAULT_ROOM_DIMENSIONS.height },
    depth: { type: 'number', default: ResonanceAudio.Utils.DEFAULT_ROOM_DIMENSIONS.depth },
 
    // Resonance audio parameters.
    ambisonicOrder: { type: 'int', default: ResonanceAudio.Utils.DEFAULT_AMBISONIC_ORDER },
    speedOfSound: { type: 'number', default: ResonanceAudio.Utils.DEFAULT_SPEED_OF_SOUND },
 
    // Room wall materials.
    left: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
    right: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
    front: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
    back: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
    down: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
    up: { default: 'brick-bare', oneOf: RESONANCE_MATERIAL },
 
    // Whether to show a visualization of the room. This shows a wireframe of the box that is considered as the room.
    visualize: { type: 'boolean', default: false }
  },
 
  init () {
    // Initialize the audio context and connect with Resonance.
    this.audioContext = new AudioContext()
    this.resonanceAudioScene = new ResonanceAudio(this.audioContext)
    this.resonanceAudioScene.output.connect(this.audioContext.destination)
 
    // Collection of audio sources.
    this.sources = []
    this.exposeAPI()
 
    // Set up the room acoustics before the audio sources are set up.
    this.updateRoomAcoustics()
 
    // Update on entity change.
    this.onEntityChange = this.onEntityChange.bind(this)
    this.el.addEventListener('componentchanged', this.onEntityChange)
 
    // When the scene has loaded and all world positions are calculated, update the visualization.
    onceWhenLoaded(this.el.sceneEl, () => {
      this.updateVisualization()
    })
  },
 
  update (oldData) {
    this.el.sceneEl.object3D.updateMatrixWorld(true)
    this.updateRoomAcoustics()
    this.toggleShowVisualization(oldData.visualize, this.data.visualize)
    this.updateVisualization()
  },
 
  tock () {
    // Calculate camera position relative to room.
    this.resonanceAudioScene.setListenerFromMatrix(
      new THREE.Matrix4().multiplyMatrices(
        new THREE.Matrix4().copy(this.el.object3D.matrixWorld).invert(),
        this.el.sceneEl.camera.el.object3D.matrixWorld
      )
    )
  },
 
  remove () {
    [...this.sources].map(source => source.leaveRoom())
    this.toggleShowVisualization(this.data.visualize, false)
    this.el.removeEventListener('componentchanged', this.onEntityChange)
  },
 
  /**
   * Update room acoustics.
   */
  updateRoomAcoustics () {
    this.resonanceAudioScene.setRoomProperties({
      width: this.data.width,
      height: this.data.height,
      depth: this.data.depth
    }, {
      left: this.data.left,
      right: this.data.right,
      front: this.data.front,
      back: this.data.back,
      down: this.data.down,
      up: this.data.up
    })
    this.resonanceAudioScene.setAmbisonicOrder(this.data.ambisonicOrder)
    this.resonanceAudioScene.setSpeedOfSound(this.data.speedOfSound)
  },
 
  /**
   * Toggle showing the visualization.
   * @param {boolean} previous - the previous setting
   * @param {boolean} current - the new setting
   * @returns {this}
   */
  toggleShowVisualization (previous, current) {
    // This is done to the root so it is not affected by the current entity.
    if (!previous && current) {
      this.el.setObject3D(
        visName,
        new THREE.Mesh(
          new THREE.BoxBufferGeometry(this.data.width, this.data.height, this.data.depth),
          new THREE.MeshStandardMaterial({
            color: 0xffffff,
            metalness: 0,
            wireframe: true,
            visible: true
          })
        )
      )
    } else if (previous && !current && this.el.getObject3D(visName)) {
      this.el.removeObject3D(visName)
    }
    return this
  },
 
  /**
   * Update the visualization of this audio room according to the properties set.
   * @returns {this}
   */
  updateVisualization () {
    const d = this.data
    const v = this.el.getObject3D(visName)
    const params = v && v.geometry.parameters
    if (d.visualize && v &&
       (d.width !== params.width || d.height !== params.height || d.depth !== params.depth)) {
      this.toggleShowVisualization(true, false)
      this.toggleShowVisualization(false, true)
    }
    return this
  },
 
  /**
   * When the entity's position or rotation is changed, update visualization and sources
   * accordingly.
   * @param {Event} evt
   */
  onEntityChange (evt) {
    if (evt.detail.name !== 'position' && evt.detail.name !== 'rotation') { return }
 
    this.sources.forEach(source => source.updateResonancePosition())
  },
 
  /**
   * Expose two collections on the element for easy access:
   * - audioSources: the connected resonance-audio-src components.
   * - sounds: the connected HTMLMediaElement and MediaStream objects.
   */
  exposeAPI () {
    Object.defineProperties(this.el, {
      // Array of audio source components.
      audioSources: { enumerable: true, get: () => this.sources },
      // Array of audio sources (HTMLMediaElement and MediaStream objects).
      sounds: { enumerable: true, get: () => this.sources.map(source => source.sound) }
    })
  },
 
  /**
   * Store audio source.
   * @param {HTMLElement} el
   */
  store (el) {
    // Only consider relevant elements.
    Iif (!el || !el.components || !('resonance-audio-src' in el.components)) { return }
 
    this.sources.push(el.components['resonance-audio-src'])
  },
 
  /**
   * Forget audio source by forgetting its component reference.
   * @param {HTMLElement} el - the audio source
   */
  forget (el) {
    const source = el.components['resonance-audio-src']
    Iif (!source || !this.sources.includes(source)) { return }
 
    this.sources.splice(this.sources.indexOf(source), 1)
  }
})
 
/**
 * Composite bounding box component. Use this one if the room should be the bounding box of the
 * entity this component is attached to.
 */
 AFRAME.registerComponent('resonance-audio-room-bb', {
  dependencies: ['position', 'geometry'],
  schema: AFRAME.components['resonance-audio-room'].schema,
  init () {
    if (this.el.components['obj-model'] && !this.el.components['obj-model'].model) {
      // If bounded by a model.
      this.setRoom(this.data)
      this.el.addEventListener('model-loaded', () => {
        this.setFromBB()
        this.el.emit('bounded-audioroom-loaded', { room: this.el })
      })
    } else {
      // If bounded by a different geometry.
      this.setFromBB(this.data)
      this.el.emit('bounded-audioroom-loaded', { room: this.el })
    }
  },
  setFromBB (base = {}) {
    // TODO: make a better bounding box, taking into account the centrepoint position of the entity.
    const size = getBoundingBox(this.el.object3D).getSize()
    this.setRoom({ ...base, width: size.x, height: size.y, depth: size.z })
  },
  setRoom (values) {
    this.el.setAttribute('resonance-audio-room', values)
  }
})
 
AFRAME.registerPrimitive('a-resonance-audio-room', {
  defaultComponents: {
    'resonance-audio-room': {}
  },
  mappings: {
    width: 'resonance-audio-room.width',
    height: 'resonance-audio-room.height',
    depth: 'resonance-audio-room.depth',
    'ambisonic-order': 'resonance-audio-room.ambisonicOrder',
    'speed-of-sound': 'resonance-audio-room.speedOfSound',
    left: 'resonance-audio-room.left',
    right: 'resonance-audio-room.right',
    front: 'resonance-audio-room.front',
    back: 'resonance-audio-room.back',
    down: 'resonance-audio-room.down',
    up: 'resonance-audio-room.up',
    visualize: 'resonance-audio-room.visualize'
  }
})