音频管理器(初步)
现在我们来抽象出音频管理器 AudioManager.
AudioManager 单例
1、在 assets/fw/
文件夹下新建 audio
文件夹,audio 文件夹下新建 AudioManager.ts 文件
2、AudioManager.ts 实现单例模式
/** 单例模式的音频管理器 */
export class AudioManager {
private static _instance: AudioManager = null!;
/** 获取单例的接口 */
static getInstance() {
if (this._instance === null) {
this._instance = new AudioManager();
}
return this._instance;
}
private constructor() {
// 私有化的构造函数
}
}
3、音频管理器提供播放接口
3.1 音频管理器需要 AudioSource 控制播放,因此从正在运行的场景获得 Canvas 节点,并在其上添加 AudioSource 组件
export class AudioManager {
/** ======== 之前的单例模式实现代码 ======== */
/** AudioSource 挂载在此节点上 */
private m_AttachNode: Node = null;
/** AudioSource 组件 */
private m_AudioSource: AudioSource = null;
private constructor() {
// 私有化的构造函数
this.m_AttachNode = director.getScene().getChildByName("Canvas");
this.m_AudioSource = this.m_AttachNode.addComponent(AudioSource);
}
3.2 添加播放 API
目前我们先提供一个简单的 playMusic 接口,用于播放背景音乐
export class AudioManager {
/** ======== 其他代码 ======== */
/** 默认播放背景音乐接口 */
playMusic(bUrl: {
/** * 子包名 */ b: string,
/** * 资源路径 */ l: string,
}): void {
// 加载背景音乐后播放
ResManager.getInstance().loadAudioClip(bUrl.b, bUrl.l, audioClip => {
let audioSource = this.m_AudioSource;
audioSource.clip = audioClip;
audioSource.loop = true;
audioSource.play();
})
}
}
4、改造 LoginEntry 中的播放背景音乐实现
import { _decorator, Component, instantiate, UITransform } from 'cc';
import { G_VIEW_SIZE } from '../../Boost';
import { AudioManager } from '../../fw/audio/AudioManager';
import { ResManager } from '../../fw/res/ResManager';
const { ccclass, property } = _decorator;
@ccclass('LoginEntry')
export class LoginEntry extends Component {
start() {
this.scheduleOnce(() => {
ResManager.getInstance().loadPrefab("Match3BN", "Match3UI", prefab => {
let match3Node = instantiate(prefab);
this.node.addChild(match3Node);
match3Node.getComponent(UITransform).setContentSize(G_VIEW_SIZE.clone());
});
// 加载背景音乐后播放
AudioManager.getInstance().playMusic({
b: "Match3BN",
l: "Audio/bgm"
})
}, 1)
}
}
点击运行,完美!
当然,音频模块还不是最终版本,这里涉及到多个音频同时播放的问题,背景和音效的区别,音频的音量设置、静音功能、多平台适配、音频中断恢复逻辑等。当然如果对音频有更高的要求,比如做音游的游戏来说,可能需要引入更专业的音频库。
对新手来说,只能先入门,再深入。