|
1 | | -export function getAudioContext() { |
2 | | - const audioCtx = new AudioContext(); |
3 | | - return audioCtx; |
| 1 | +export class notePlayer { |
| 2 | + private audioCtx: AudioContext; |
| 3 | + private gainNode: GainNode; |
| 4 | + private oscillator: OscillatorNode; |
| 5 | + private DEFAULT_FREQUENCY = 440; |
| 6 | + constructor() { |
| 7 | + this.audioCtx = new AudioContext(); |
| 8 | + |
| 9 | + this.gainNode = this.audioCtx.createGain(); |
| 10 | + |
| 11 | + this.oscillator = this.audioCtx.createOscillator(); |
| 12 | + this.oscillator.connect(this.gainNode); |
| 13 | + |
| 14 | + this.setOscillatorDefaultSettings(); |
| 15 | + this.oscillator.start(); |
| 16 | + } |
| 17 | + |
| 18 | + private setOscillatorDefaultSettings() { |
| 19 | + this.oscillator.frequency.setValueAtTime( |
| 20 | + this.DEFAULT_FREQUENCY, |
| 21 | + this.audioCtx.currentTime |
| 22 | + ); |
| 23 | + this.oscillator.type = "sine"; |
| 24 | + } |
| 25 | + |
| 26 | + setOscillatorType(type: OscillatorType) { |
| 27 | + this.oscillator.type = type; |
| 28 | + } |
| 29 | + setFrequency(frequency: number) { |
| 30 | + this.oscillator.frequency.setValueAtTime( |
| 31 | + frequency, |
| 32 | + this.audioCtx.currentTime |
| 33 | + ); |
| 34 | + } |
| 35 | + setGain(gain: number) { |
| 36 | + this.gainNode.gain.setValueAtTime(gain, this.audioCtx.currentTime); |
| 37 | + } |
| 38 | + |
| 39 | + play(frequency?: number) { |
| 40 | + if (frequency) { |
| 41 | + this.setFrequency(frequency); |
| 42 | + } |
| 43 | + this.gainNode.connect(this.audioCtx.destination); |
| 44 | + } |
| 45 | + stop() { |
| 46 | + this.gainNode.disconnect(this.audioCtx.destination); |
| 47 | + } |
4 | 48 | } |
0 commit comments