Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(noise.js):Add webaudio noise class
- Loading branch information
1 parent
2a74ef9
commit 49a7ab4
Showing
3 changed files
with
72 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
export default class Noise { | ||
constructor () { | ||
try { | ||
const AudioContext = window.AudioContext || window.webkitAudioContext | ||
this.context = new AudioContext(); | ||
} catch (e) { | ||
throw new Error('Web Audio isn\'t supported in this browser!'); | ||
} | ||
this.createSource() | ||
this.playing = false | ||
} | ||
|
||
createSource() { | ||
const node = this.context.createBufferSource() | ||
const buffer = this.context.createBuffer(1, this.context.sampleRate, this.context.sampleRate) | ||
const data = buffer.getChannelData(0) | ||
for (let i = 0; i < this.context.sampleRate; i++) { | ||
data[i] = Math.random(); | ||
} | ||
node.buffer = buffer | ||
node.loop = true | ||
this.gain = this.context.createGain() | ||
this.gain.gain.value = 0.01 | ||
node.connect(this.gain) | ||
this.bandpass = this.context.createBiquadFilter() | ||
this.gain.connect(this.bandpass) | ||
this.bandpass.connect(this.context.destination) | ||
this.source = node | ||
this.setVolume(0) | ||
} | ||
|
||
setVolume (v) { | ||
v = Math.max(0, Math.min(1, v)) | ||
this.gain.gain.value = v | ||
} | ||
|
||
setFrequency (freq) { | ||
this.bandpass.frequency.value = freq > 22050 ? 22050 : freq | ||
} | ||
|
||
start () { | ||
if (!this.playing) { | ||
this.playing = true | ||
this.source.start(0) | ||
} | ||
} | ||
|
||
stop() { | ||
if (this.playing) { | ||
this.playing = false | ||
this.source.stop() | ||
this.createSource() | ||
} | ||
} | ||
} |