音频播放管理器示例

由于 Cocos Creator 3.x 移除了 v2.x cc.audioEngine 系列的 API,统一使用 AudioSource 控制音频播放。

但在实际项目开发中,我们仍然需要一个方便随时调用的音频播放管理器,可参考或直接使用以下代码:

  1. //AudioMgr.ts
  2. import { Node, AudioSource, AudioClip, resources, director } from 'cc';
  3. /**
  4. * @en
  5. * this is a sington class for audio play, can be easily called from anywhere in you project.
  6. * @zh
  7. * 这是一个用于播放音频的单件类,可以很方便地在项目的任何地方调用。
  8. */
  9. export class AudioMgr {
  10. private static _inst: AudioMgr;
  11. public static get inst(): AudioMgr {
  12. if (this._inst == null) {
  13. this._inst = new AudioMgr();
  14. }
  15. return this._inst;
  16. }
  17. private _audioSource: AudioSource;
  18. constructor() {
  19. //@en create a node as audioMgr
  20. //@zh 创建一个节点作为 audioMgr
  21. let audioMgr = new Node();
  22. audioMgr.name = '__audioMgr__';
  23. //@en add to the scene.
  24. //@zh 添加节点到场景
  25. director.getScene().addChild(audioMgr);
  26. //@en make it as a persistent node, so it won't be destroied when scene change.
  27. //@zh 标记为常驻节点,这样场景切换的时候就不会被销毁了
  28. director.addPersistRootNode(audioMgr);
  29. //@en add AudioSource componrnt to play audios.
  30. //@zh 添加 AudioSource 组件,用于播放音频。
  31. this._audioSource = audioMgr.addComponent(AudioSource);
  32. }
  33. public get audioSource() {
  34. return this._audioSource;
  35. }
  36. /**
  37. * @en
  38. * play short audio, such as strikes,explosions
  39. * @zh
  40. * 播放短音频,比如 打击音效,爆炸音效等
  41. * @param sound clip or url for the audio
  42. * @param volume
  43. */
  44. playOneShot(sound: AudioClip | string, volume: number = 1.0) {
  45. if (sound instanceof AudioClip) {
  46. this._audioSource.playOneShot(sound, volume);
  47. }
  48. else {
  49. resources.load(sound, (err, clip: AudioClip) => {
  50. if (err) {
  51. console.log(err);
  52. }
  53. else {
  54. this._audioSource.playOneShot(clip, volume);
  55. }
  56. });
  57. }
  58. }
  59. /**
  60. * @en
  61. * play long audio, such as the bg music
  62. * @zh
  63. * 播放长音频,比如 背景音乐
  64. * @param sound clip or url for the sound
  65. * @param volume
  66. */
  67. play(sound: AudioClip | string, volume: number = 1.0) {
  68. if (sound instanceof AudioClip) {
  69. this._audioSource.clip = sound;
  70. this._audioSource.play();
  71. this.audioSource.volume = volume;
  72. }
  73. else {
  74. resources.load(sound, (err, clip: AudioClip) => {
  75. if (err) {
  76. console.log(err);
  77. }
  78. else {
  79. this._audioSource.clip = clip;
  80. this._audioSource.play();
  81. this.audioSource.volume = volume;
  82. }
  83. });
  84. }
  85. }
  86. /**
  87. * stop the audio play
  88. */
  89. stop() {
  90. this._audioSource.stop();
  91. }
  92. /**
  93. * pause the audio play
  94. */
  95. pause() {
  96. this._audioSource.pause();
  97. }
  98. /**
  99. * resume the audio play
  100. */
  101. resume(){
  102. this._audioSource.play();
  103. }
  104. }