cocos支持的音效格式:

支持的音乐格式
Android mp3, mid, ogg, wav 可以播放android.media.MediaPlayer所支持的所有格式
iOS aac, caf, mp3, m4a, wav 可以播放AVAudioPlayer所支持的所有格式
Windows mid, mp3, wav
支持的音效格式
Android ogg, wav 对wav的支持不完美
iOS caf, m4a 可以播放Cocos2d-iPhone CocosDesion所支持的所有格式
Windows mid, wav

一、预加载

加载音乐和音效通常是个耗时间的过程,为了防止由加载产生的延时导致实际播放与游戏播放不协调的现象,在播放音乐和音效前,可以预加载音乐文件。

  1. class EXPORT_DLL SimpleAudioEngine
  2. {
  3. virtual void preloadBackgroundMusic(const char* filePath);
  4. // Preload a compressed audio file.
  5. // The compressed audio will be decoded to wave, then written into
  6. // an internal buffer in SimpleAudioEngine.
  7. virtual void preloadEffect(const char* filePath);
  8. // Unload the preloaded effect from internal buffer.
  9. virtual void unloadEffect(const char* filePath);
  10. }

使用示例:

  1. #include "SimpleAudioEngine.h"
  2. using namespace CocosDenshion;
  3. auto audio = SimpleAudioEngine::getInstance();
  4. // pre-loading background music and effects. You could pre-load
  5. // effects, perhaps on app startup so they are already loaded
  6. // when you want to use them.
  7. audio->preloadBackgroundMusic("myMusic1.mp3");
  8. audio->preloadBackgroundMusic("myMusic2.mp3");
  9. audio->preloadEffect("myEffect1.mp3");
  10. audio->preloadEffect("myEffect2.mp3");
  11. // unload a sound from cache. If you are finished with a sound and
  12. // you wont use it anymore in your game. unload it to free up resources.
  13. audio->unloadEffect("myEffect1.mp3");

二、播放控制

  1. class EXPORT_DLL SimpleAudioEngine
  2. {
  3. // 播放音乐
  4. // filePath: path of the background music file,or the FileName of T_SoundResInfo.
  5. virtual void playBackgroundMusic(const char* filePath, bool loop = false);
  6. // 重头放
  7. virtual void rewindBackgroundMusic();
  8. // 播放音效,返回 sound id。有以下支持限制:
  9. // - no pitch effect on Samsung Galaxy S2 with OpenSL backend enabled;
  10. // - no pitch/pan/gain on win32.
  11. virtual unsigned int playEffect(const char* filePath,
  12. bool loop = false,
  13. float pitch = 1.0f, // 频率
  14. float pan = 0.0f, // 立体音效,-1.0 ~ 1.0,-1.0左声道
  15. float gain = 1.0f); // 音量,0.0 ~ 1.0
  16. // 停止播放,soundId失效,cache还在,需要unload
  17. virtual void stopBackgroundMusic(bool releaseData = false);
  18. virtual void stopEffect(unsigned int soundId);
  19. virtual void stopAllEffects();
  20. // 暂停播放
  21. virtual void pauseEffect(unsigned int soundId);
  22. virtual void pauseAllEffects();
  23. virtual void pauseBackgroundMusic();
  24. // 恢复播放
  25. virtual void resumeEffect(unsigned int soundId);
  26. virtual void resumeAllEffects();
  27. virtual void resumeBackgroundMusic();
  28. // 音量控制,0.0 <= volume <= 1.0
  29. virtual void setBackgroundMusicVolume(float volume);
  30. virtual void setEffectsVolume(float volume);
  31. }