all files / src/ Sounder.js

100% Statements 18/18
100% Branches 8/8
100% Functions 4/4
100% Lines 16/16
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                16×   15×   15× 14×   13×                                                  
/**
 * Outputs sound using the Web Audio API
 * @private
 * @param {AudioContext} context - the Web Audio API context
 * @param {number} numberOfSeries - number of data series
 */
class Sounder {
	constructor(context, numberOfSeries) {
		if (context === undefined) {
			throw Error('No audio context given')
		}
		this._context = context
 
		if (numberOfSeries === undefined) {
			throw Error('No number of data series given')
		} else if (numberOfSeries > 2) {
			throw Error('Large number of data series given')
		}
		this._numberOfSeries = numberOfSeries
	}
 
	/**
	 * Start the oscillator(s)
	 */
	start() {
		// Oscillators cannot be re-used
		this._oscillators = []
		for (let i = 0; i < this._numberOfSeries; i++) {
			this._oscillators[i] = this._context.createOscillator()
			if (i === 1) this._oscillators[i].type = 'square'
			this._oscillators[i].connect(this._context.destination)
			this._oscillators[i].start(0)
		}
	}
 
	/**
	 * Set the frequency of the oscillator for a given series
	 * @param {number} series - set frequency for which series?
	 * @param {number} frequency - the frequency to change to (Hz)
	 */
	frequency(series, frequency) {
		this._oscillators[series].frequency.value = frequency
	}
 
	/**
	 * Stop the oscillator(s)
	 */
	stop() {
		this._oscillators.forEach((oscillator) => oscillator.stop())
	}
}