| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import {_decorator, AudioClip, AudioSource, Component, Node, resources} from 'cc';
- const {ccclass, property} = _decorator;
- @ccclass('AudioManage')
- export class AudioManage extends Component {
- private static _instance: AudioManage;
- private static _audioSource?: AudioSource;
- static get instance() {
- if (this._instance) {
- return this._instance;
- }
- this._instance = new AudioManage();
- return this._instance;
- }
- protected onLoad(): void {
- this.init();
- }
- init() {
- AudioManage._audioSource = this.node.getComponent(AudioSource);
- }
- //播放音乐
- playMusic(loop: boolean = true) {
- const audioSource = AudioManage._audioSource!;
- audioSource.loop = loop;
- if (!audioSource.playing) {
- audioSource.play();
- }
- }
- //暂停音乐
- pauseMusic() {
- const audioSource = AudioManage._audioSource!;
- if (audioSource.playing) {
- audioSource.stop();
- }
- }
- /**
- * 播放音效
- * @param {String} name 音效名称
- * @param {Number} volumeScale 播放音量倍数
- */
- playSound(name: string, volumeScale: number = 1) {
- const audioSource = AudioManage._audioSource!;
- resources.load(name, AudioClip, (err: any, ac) => {
- audioSource.playOneShot(ac, volumeScale);
- });
- }
- setBgVolume(value: number) {
- const audioSource = AudioManage._audioSource!;
- audioSource.volume = value;
- }
- /**
- * 播放音效带回调
- * @param name
- * @param volumeScale
- * @param onEnd
- */
- playSoundCallback(name: string, volumeScale: number = 1, isLoop: boolean = false, onEnd?: Function, callback?: any) {
- const audioSource = AudioManage._audioSource!;
- audioSource.node.off(AudioSource.EventType.ENDED)
- audioSource.node.on(AudioSource.EventType.ENDED, onEnd, callback)
- audioSource.loop = isLoop
- // audioSource.volume = volumeScale
- resources.load(name, AudioClip, (err: any, ac) => {
- if (err) {
- console.log(err);
- } else {
- audioSource.clip = ac
- audioSource.play();
- }
- });
- }
- }
|