-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudio.js
More file actions
55 lines (43 loc) · 1.51 KB
/
audio.js
File metadata and controls
55 lines (43 loc) · 1.51 KB
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
import { vec2 } from './gl-matrix-min.js'
//the global collection of sounds
let sounds = {}
//ambient Audio handles
export let walk_wood = null;
export let music;
//TODO currently it is impossible to play the same audio from multiple positions
export let PositionalAudio = function(pos, name, loop) {
this.name = name;
sounds[name] = this; //register globally
this.sound = new Audio(name);
if (loop)
this.sound.loop = true;
this.pos = vec2.clone(pos);
}
//base audio functions
PositionalAudio.prototype.play = function() { this.sound.play(); }
PositionalAudio.prototype.pause = function() { this.sound.pause(); }
PositionalAudio.prototype.stop = function() {
this.sound.pause();
this.sound.currentTime = 0;
}
//set volume based on distance to audio source
PositionalAudio.prototype.update = function(listenPos) {
this.sound.volume = 1 / Math.max(1, vec2.dist(listenPos, this.pos));
}
//manipulate position of audio source.
PositionalAudio.prototype.moveTo = function(newPos) { vec2.copy(this.pos, newPos); }
PositionalAudio.prototype.move = function(trans) { vec2.add(this.pos, this.pos, trans); }
//create ambient audio
export function initAudio() {
walk_wood = new Audio("assets/walk_wood.ogg");
walk_wood.loop = true;
music = new Audio("assets/music1.ogg");
music.volume = 0.2;
music.loop = true;
}
//update volume of all positional sounds.
export function updateAudio(listener) {
for (let soundID in sounds)
if (typeof sounds[soundID].update === "function")
sounds[soundID].update(listener);
}