preface
** Keywords: ** sound effects, background music, game development,Cocos Creator, game music
In game development, we often need to use sound to create the atmosphere of the game, so this article summarizes the packaging and use of sound components in Cocos Creator game development.
I. Audio playback basis in Cocos Creator
1. Basic knowledge
【 1 】 AudioSource component official documentation: docs.cocos.com/creator/man…
[2] cc. AudioEngine official document: docs.cocos.com/creator/man…
Cocos Creator provides two ways to play audio. Both AudioEngine and AudioSource can play audio. The difference is that the AudioSource is a component that can be added to the scene and set by the editor. AudioEngine is a pure API provided by the engine and can only be called in scripts.
** Common ground: ** Essentially works with AudioClip audio resources and requires a component to be mounted in the Cocos Creator editor.
I suggest using this to replace the AudioSource component playback sound, complete interface, effective test, you can package a script similar to the AudioSource component to use.
Method 1: Use the AudioSource component to play
Create an empty node and on this empty node, add another component -> AudioSource
The AudioSource should be preset on the script, and the external interface of the script should be improved according to the actual requirements, as follows:
1. `cc.Class({` 2. `properties: {` 3. `audioSource: {` 4. `type: cc.AudioSource, default: null` 5. `}, }, play() {` 6. `this.audioSource.play(); ` 7. `}, pause () {` 8. `this.audioSource.pause(); ` 9. `}}); `Copy the code
Method 2: Use AudioEngine to play
Define an audioClip resource object in the script, as in the properties object in the following example.
Cc. AudioEngine. Play (audio, loop, volume); Play. In onLoad in the following example.
1. `cc.Class({`
2. `properties: {`
3. `audio: {`
4. `default: null, type: cc.AudioClip`
5. `}`
6. `}, onLoad() {`
7. `this.current = cc.audioEngine.play(this.audio, false, 1);`
8. `}, onDestroy() {`
9. `cc.audioEngine.stop(this.current);`
10. `}`
11. `});`
Copy the code
When AudioEngine plays, note that it is passing in a complete AudioClip object (not a URL). So instead of putting the URL of the audio in the Play interface, we want you to define an AudioClip and drag the audio in the editor.
2. Common methods
[1] Component AudioSource
1. 'play () plays the audio clip. 2. 'stop () Stops the current audio clip. '3.' pause () Pauses the current audio clip. '4.' Resume () '. 5. 'Rewind () play from the beginning. `Copy the code
[2] Sound system cc. AudioEngine
1. '// Background music, loop' 2. 'cc.audioengine. PlayMusic (source); ` 3. `cc.audioEngine.stopMusic(source); ` 4. ` / / short sound ` 5. ` cc. AudioEngine. PlayEffect (source); ` 6. `cc.audioEngine.stopEffect(source); `Copy the code
The first method above has a lot of bugs on the native platform, so our games use the second method for sound playback.
Second, Cocos Creator sound management component package
- Create the sound management class SoundMgr.ts
1. `const{ccclass, property} = cc._decorator; ` 2. `@ccclass` 3. `exportdefaultclassSoundMgr{` 4. `sound_path:string= 'res/sounds/'; '6.' sounds:{[key:string]:any} = {}; ` 7. `enabled:boolean= true; ` 8. `music:string= ''; // Singleton mode '10.' Protectedstatic instance:SoundMgr; ` 11. `publicstatic getInstance():SoundMgr{` 12. `if(! this.instance){` 13. `this.instance = newSoundMgr(); ` 14. `}` 15. `returnthis.instance; 'addSound(key:string, clip:cc.AudioClip){' 19.' This. ` 20. `}` 21. `playFx(fxName:string){` 22. `if(! this.enabled) return; ` 23. `cc.audioEngine.playEffect(this.sounds[fxName], false); ` 24. `}` 25. `playMusic(musicName:string){` 26. `this.music = musicName; ` 27. `if(! this.enabled) return; ` 28. `cc.audioEngine.playMusic(this.sounds[musicName], true); ` 29. `}` 30. `stopMusic(){` 31. `cc.audioEngine.stopMusic(); ` 32. `}` 33. `setEnabled(enabled:boolean){` 34. `this.enabled = enabled; ` 35. `if(this.enabled){` 36. `this.playMusic(this.music); ` 37. `}else{` 38. `cc.audioEngine.stopAll(); ` 39. `}` 40. `}` 41. `getEnable(){` 42. `returnthis.enabled; '43.'} '44.'}Copy the code
Since we only need one sound management class for the entire game, we made the marketing management class a singleton in the code above. In the Sounds property, you hold the name of the sound and the key-value pair of the sound resource object. It can be obtained by the key value of the sound file during playback.
2. Load audio resources during initialization
Using the Cocos Creator visual editing tool, we set up the game scene and resources as follows:
Since “Sounds” is loaded dynamically by code, we put the “Sounds” folder where we saved all the sound files into the Resources folder (as shown above).
Then, create gamemgr. ts and mount it to the Canvas node.
1. `const{ccclass, property} = cc._decorator; ` 2. `importSoundMgrfrom"SoundMgr"; ` 3. ` @ ccclass ` 4. ` exportdefaultclassGameMgrextends cc.Com ponent {` 5. ` loadSounds () {` 6. ` / / attention through code dynamically loaded resources must be put Loader. loadResDir('sounds', cc.AudioClip, function(err, clips){` 8. `console.log("load clips:",clips); ` 9. `if(err){` 10. `console.log("err:",err); ` 11. `}` 12. `for(let i=0; i<clips.length; i++){` 13. `SoundMgr.getInstance().addSound(clips[i].name, clips[i]); '14.'} '15.'}); ` 16. `}` 17. `onLoad () {` 18. `this.loadSounds(); ` 19. `console.log("sounds:",SoundMgr.getInstance().sounds); ` 20. `}` 21. `onPlayClick(){` 22. `console.log("play"); ` 23. `SoundMgr.getInstance().playMusic('spring_music'); ` 24. `}` 25. `onPauseClick(){` 26. `console.log("pause"); ` 27. `SoundMgr.getInstance().stopMusic(); '28.'} '29.'} 'Copy the code
In the onLoad method of the GameMgr custom component, loadSounds is called to load all the sound resources needed in the game. Gamemgr. ts also provides play and pause interface methods onPlayClick and onPauseClick.
Called by the Play and pause buttons.
3. Play and pause the call
4. Run the tests
All sound resources are loaded successfully, and click the play and pause buttons to pass the test.
Three, notes
Note: If the audio playback Settings are complete, some browsers preview or run without hearing the sound, it may be due to browser compatibility problems. Such as: Chrome disables WebAudio autoplay, and Audio is loaded and played using WebAudio by default. In this case, users need to select the Audio resource in explorer. Then, in the property inspector, change the loading mode of the Audio to DOM Audio for it to play properly on the browser.
The last
Need project source code friends, you can contact us in the comments section or the public number message.