音频播放示例
import { AudioClip, AudioSource, assert, warn, clamp01, resources } from "cc";
export class audioManager {
private static _instance: audioManager;
private static _audioSource?: AudioSource;
static get instance () {
if (this._instance) {
return this._instance;
}
this._instance = new audioManager();
return this._instance;
}
/**管理器初始化*/
init (audioSource: AudioSource) {
audioManager._audioSource = audioSource;
/**
* 播放音乐
* @param {Boolean} loop 是否循环播放
*/
playMusic (loop: boolean) {
const audioSource = audioManager._audioSource!;
assert(audioSource, 'AudioManager not inited!');
audioSource.loop = loop;
if (!audioSource.playing) {
audioSource.play();
}
}
/**
* 播放音效
* @param {String} name 音效名称
*/
playSound (name: string, volumeScale: number = 1 ) {
const audioSource = audioManager._audioSource!;
assert(audioSource, 'AudioManager not inited!');
// 注意:第二个参数 “volumeScale” 是指播放音量的倍数,最终播放的音量为 “audioSource.volume * volumeScale”
audioSource.playOneShot(audioClip, volumeScale);
}
// 设置音乐音量
setMusicVolume (flag: number) {
const audioSource = audioManager._audioSource!;
assert(audioSource, 'AudioManager not inited!');
flag = clamp01(flag);
audioSource.volume = flag;
}