import { AudioClip, AudioSource, CCClass, Component, Node, _decorator } from "cc";
const { ccclass } = _decorator;
@ccclass('AudioEngine')
export class AudioEngine extends Component {
public static Instance: AudioEngine;
private _volume: number = 1;
private _bgmName: string = "";
onLoad() {
if (AudioEngine.Instance == null) {
AudioEngine.Instance = this;
}
else {
this.destroy()
return;
}
}
public playMusic(clip: AudioClip, loop: boolean): string {
return this.playAudio(clip, loop, true);
}
public playEffect(clip: AudioClip, loop: boolean): string {
return this.playAudio(clip, loop, false);
}
public resumeBgm(): void {
let as = this.getAudioSourceNode(this._bgmName);
if (as && as.state == AudioSource.AudioState.PAUSED) {
as.play();
}
}
public resumeAll(): void {
this.node.children.forEach(element => {
let as = element.getComponent(AudioSource);
if (as.state == AudioSource.AudioState.PAUSED) {
as.play();
}
});
}
public pauseAll(): void {
this.node.children.forEach(element => {
let as = element.getComponent(AudioSource);
as.pause();
});
}
public stopMusic(): void {
let as = this.getAudioSourceNode(this._bgmName);
if (as) {
as.stop();
}
}
public stopEffect(name: string): void {
this.stop(name);
}
public stop(name: string): void {
let as = this.getAudioSourceNode(name);
if (as) {
as.stop();
}
}
public stopAll(): void {
this.node.children.forEach(element => {
let as = element.getComponent(AudioSource);
as.stop();
});
}
public getVolume(name: string): number {
let as = this.getAudioSourceNode(name);
if (as) {
return as.volume;
}
return 0;
}
public setVolume(name: string, volume): void {
let as = this.getAudioSourceNode(name);
if (as) {
as.volume = volume;
}
}
public setFinishCallback(name: string, func: Function): void {
let as = this.getAudioSourceNode(name);
if (as) {
as.clip.once('ended', (err, data) => {
if (func) {
func()
}
})
}
}
public isPlaying(name: string): boolean {
let as = this.getAudioSourceNode(name);
if (as) {
return as.playing;
}
else {
return false;
}
}
private playAudio(clip: AudioClip, loop: boolean, isBgm): string {
let as: AudioSource = null
if (isBgm) {
if (this._bgmName != "") {
as = this.getAudioSourceNode(this._bgmName);
}
this._bgmName = clip.name;
}
if (as == null) {
as = this.getAudioSourceNode(clip.name);
}
if (as.playing) {
as.pause();
}
as.clip = clip;
as.loop = loop;
as.volume = this._volume
as.play();
return clip.name;
}
private getAudioSourceNode(name: string): AudioSource {
if (this.node != null) {
let node = this.node.getChildByName(name);
if (node) {
return node.getComponent(AudioSource);
}
else {
node = new Node();
let as = node.addComponent(AudioSource);
this.node.addChild(node);
node.name = name;
return as;
}
}
return null;
}
}
CocosCreator3.x仿照2.x的AudioEngine
于 2023-11-28 16:42:34 首次发布