AudioManager.ts
3.1 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
86
87
88
89
90
91
92
93
94
95
96
import { SettingEvents } from "../../event/BaseEvents";
import { GameBasicSettings } from "../settings/GameBasicSettings";
import { ResUtils } from "../../utils/ResUtils";
import { delay } from "simba-utils";
export namespace AudioManager {
let _musicPathPrefix: string = "";
let _voicePathPrefix: string = "";
let _effectPathPrefix: string = "";
export function init(musicPathPrefix = "", effectPathPrefix = "", voicePathPrefix = "") {
_musicPathPrefix = musicPathPrefix;
_voicePathPrefix = voicePathPrefix;
_effectPathPrefix = effectPathPrefix;
cc.audioEngine.setMusicVolume(GameBasicSettings.musicVolume);
cc.audioEngine.setEffectsVolume(GameBasicSettings.soundVolume);
SettingEvents.MusicVolumeChange.on((volume) => {
cc.audioEngine.setMusicVolume(volume);
if (volume === 0) {
cc.audioEngine.pauseMusic();
} else {
cc.audioEngine.resumeMusic();
}
});
SettingEvents.SoundVolumeChange.on((volume) => {
cc.audioEngine.setEffectsVolume(volume);
});
}
export async function playMusic(path: string) {
if (path[0] !== "/") path = _musicPathPrefix + path;
if (!GameBasicSettings.musicVolume) return;
try {
let clip = await ResUtils.loadRes<cc.AudioClip>(path, cc.AudioClip);
cc.audioEngine.playMusic(clip, true);
} catch (e) {
console.error(e);
}
}
export function pauseMusic() {
cc.audioEngine.pauseMusic();
}
export function resumeMusic() {
cc.audioEngine.resumeMusic();
}
export function stopMusic() {
cc.audioEngine.stopMusic();
}
export async function playEffect(path: string, loopCount = 1) {
if (path[0] !== "/") path = _effectPathPrefix + path;
if (!GameBasicSettings.soundVolume) return NaN;
try {
let clip = await ResUtils.loadRes<cc.AudioClip>(path, cc.AudioClip);
if (loopCount <= 0) {
return cc.audioEngine.playEffect(clip, true);
} else {
for (let i = 0; i < loopCount; i++) {
let id = cc.audioEngine.playEffect(clip, false);
let time = cc.audioEngine.getDuration(id);
await delay(time);
}
return NaN;
}
} catch (e) {
console.error(e);
}
}
export async function playVoice(path: string) {
if (path[0] !== "/") path = _voicePathPrefix + path;
stopAllEffect();
try {
let clip = await ResUtils.loadRes<cc.AudioClip>(path, cc.AudioClip);
let id = cc.audioEngine.playEffect(clip, false);
let time = cc.audioEngine.getDuration(id);
await delay(time);
} catch (e) {
console.error(e);
}
}
export function stopEffect(id: number) {
if (!isNaN(id)) {
cc.audioEngine.stopEffect(id);
}
}
export function stopAllEffect() {
cc.audioEngine.stopAllEffects();
}
}