音频播放示例

    1. import { AudioClip, AudioSource, assert, warn, clamp01, resources } from "cc";
    2. export class audioManager {
    3. private static _instance: audioManager;
    4. private static _audioSource?: AudioSource;
    5. static get instance () {
    6. if (this._instance) {
    7. return this._instance;
    8. }
    9. this._instance = new audioManager();
    10. return this._instance;
    11. }
    12. /**管理器初始化*/
    13. init (audioSource: AudioSource) {
    14. audioManager._audioSource = audioSource;
    15. /**
    16. * 播放音乐
    17. * @param {Boolean} loop 是否循环播放
    18. */
    19. playMusic (loop: boolean) {
    20. const audioSource = audioManager._audioSource!;
    21. assert(audioSource, 'AudioManager not inited!');
    22. audioSource.loop = loop;
    23. if (!audioSource.playing) {
    24. audioSource.play();
    25. }
    26. }
    27. /**
    28. * 播放音效
    29. * @param {String} name 音效名称
    30. */
    31. playSound (name: string, volumeScale: number = 1 ) {
    32. const audioSource = audioManager._audioSource!;
    33. assert(audioSource, 'AudioManager not inited!');
    34. // 注意:第二个参数 “volumeScale” 是指播放音量的倍数,最终播放的音量为 “audioSource.volume * volumeScale”
    35. audioSource.playOneShot(audioClip, volumeScale);
    36. }
    37. // 设置音乐音量
    38. setMusicVolume (flag: number) {
    39. const audioSource = audioManager._audioSource!;
    40. assert(audioSource, 'AudioManager not inited!');
    41. flag = clamp01(flag);
    42. audioSource.volume = flag;
    43. }