-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathmusic.js
100 lines (84 loc) · 2.28 KB
/
music.js
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import store from '../store';
// 使用 Web Audio API
const AudioContext = (
window.AudioContext ||
window.webkitAudioContext ||
window.mozAudioContext ||
window.oAudioContext ||
window.msAudioContext
);
const hasWebAudioAPI = {
data: !!AudioContext && location.protocol.indexOf('http') !== -1,
};
const music = {};
(() => {
if (!hasWebAudioAPI.data) {
return;
}
const url = './music.mp3';
const context = new AudioContext();
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
req.onload = () => {
context.decodeAudioData(req.response, (buf) => { // 将拿到的audio解码转为buffer
const getSource = () => { // 创建source源。
const source = context.createBufferSource();
source.buffer = buf;
source.connect(context.destination);
return source;
};
music.killStart = () => { // 游戏开始的音乐只播放一次
music.start = () => {};
};
music.start = () => { // 游戏开始
music.killStart();
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 3.7202, 3.6224);
};
music.clear = () => { // 消除方块
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 0, 0.7675);
};
music.fall = () => { // 立即下落
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 1.2558, 0.3546);
};
music.gameover = () => { // 游戏结束
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 8.1276, 1.1437);
};
music.rotate = () => { // 旋转
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 2.2471, 0.0807);
};
music.move = () => { // 移动
if (!store.getState().get('music')) {
return;
}
getSource().start(0, 2.9088, 0.1437);
};
},
(error) => {
if (window.console && window.console.error) {
window.console.error(`音频: ${url} 读取错误`, error);
hasWebAudioAPI.data = false;
}
});
};
req.send();
})();
module.exports = {
hasWebAudioAPI,
music,
};