forked from trungvose/angular-tetris
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsound-manager.service.ts
More file actions
85 lines (72 loc) · 1.99 KB
/
Copy pathsound-manager.service.ts
File metadata and controls
85 lines (72 loc) · 1.99 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { Injectable } from '@angular/core';
import { TetrisQuery } from '@trungk18/state/tetris/tetris.query';
const SoundFilePath = '/assets/tetris-sound.mp3';
@Injectable({
providedIn: 'root'
})
export class SoundManagerService {
private _context: AudioContext;
private _buffer: AudioBuffer;
constructor(private _query: TetrisQuery) {
}
start() {
this._playMusic(0, 3.7202, 3.6224);
}
clear() {
this._playMusic(0, 0, 0.7675);
}
fall() {
this._playMusic(0, 1.2558, 0.3546);
}
gameOver() {
this._playMusic(0, 8.1276, 1.1437);
}
rotate() {
this._playMusic(0, 2.2471, 0.0807);
}
move() {
this._playMusic(0, 2.9088, 0.1437);
}
private _playMusic(when: number, offset: number, duration: number) {
if (!this._query.isEnableSound) {
return;
}
this._loadSound().then((source) => {
source && source.start(when, offset, duration);
});
}
private _loadSound(): Promise<AudioBufferSourceNode> {
return new Promise((resolve, reject) => {
if (this._context && this._buffer) {
resolve(this._getSource(this._context, this._buffer));
return;
}
const context = new AudioContext();
const req = new XMLHttpRequest();
req.open('GET', SoundFilePath, true);
req.responseType = 'arraybuffer';
req.onload = () => {
context.decodeAudioData(
req.response,
(buffer) => {
this._context = context;
this._buffer = buffer;
resolve(this._getSource(context, buffer));
},
() => {
let msg = 'Sorry lah, cannot play sound. But I hope you still enjoy Angular Tetris!!';
alert(msg);
reject(msg);
}
);
};
req.send();
});
}
private _getSource(context: AudioContext, buffer: AudioBuffer): AudioBufferSourceNode {
let source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);
return source;
}
}