Skip to content

Commit

Permalink
add global sound volume
Browse files Browse the repository at this point in the history
  • Loading branch information
kriswep committed Apr 23, 2017
1 parent 554e067 commit c0c35af
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/sound.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
/* globals window AudioContext */
/* globals window AudioContext localStorage */
const sound = {
aCtx: undefined,
init() {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
this.aCtx = new AudioContext();

this.mainGain = this.aCtx.createGain();
this.mainGain.gain.value = localStorage.getItem('sound') || 0.8;
this.mainGain.connect(this.aCtx.destination);
},
noiseBuffer() {
const bufferSize = this.aCtx.sampleRate;
Expand All @@ -20,13 +24,14 @@ const sound = {
if (!this.aCtx) {
this.init();
}

const time = sound.aCtx.currentTime;
const noise = this.aCtx.createBufferSource();
const noiseEnvelope = this.aCtx.createGain();

noise.buffer = this.noiseBuffer();
noise.connect(noiseEnvelope);
noiseEnvelope.connect(this.aCtx.destination);
noiseEnvelope.connect(this.mainGain);

noiseEnvelope.gain.setValueAtTime(1, time);
noiseEnvelope.gain.exponentialRampToValueAtTime(0.01, time + 0.2);
Expand Down
13 changes: 11 additions & 2 deletions src/sound.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,23 @@ import 'web-audio-mock';
import sound from './sound';


// small localStorage mock
global.localStorage = {
getItem: jest.fn()
.mockImplementationOnce(() => null)
.mockImplementation(() => 1),
};

test('Sound should have a init function which inits audioContext', () => {
// mock window.webkitAudioContext, window.AudioConext is mocked through import above
window.webkitAudioContext = window.AudioContext;
window.AudioContext = undefined;
expect(sound.aCtx).not.toBeDefined();
expect(sound.init).toBeDefined();
expect(sound.init.bind(sound)).not.toThrow();
// sound.init();
expect(sound.aCtx).toBeDefined();
expect(sound.mainGain).toBeDefined();
expect(sound.mainGain.gain.value).toBe(0.8);

// remock window.AudioContext
window.AudioContext = window.webkitAudioContext;
Expand All @@ -21,8 +29,9 @@ test('Sound should have a init function which inits audioContext', () => {
expect(sound.aCtx).not.toBeDefined();
expect(sound.init).toBeDefined();
expect(sound.init.bind(sound)).not.toThrow();
// sound.init();
expect(sound.aCtx).toBeDefined();
expect(sound.mainGain).toBeDefined();
expect(sound.mainGain.gain.value).toBe(1);
});

test('Sound should have a playPlop function', () => {
Expand Down

0 comments on commit c0c35af

Please sign in to comment.