This article will talk about the loading and playback of sound and so on.
There are two sound engine options for the sound loading in the Cocos for our use. One is a relatively simple sound engine, while the other one is more complicated.
Generally speaking, if we just want to play music sound, we can choose to use the first one, and if you want to control the process of music sound, such as what to do after the playback, it will have a complete music or sound playback after the callback method.
Let's take a look at the first type:
This class is named Simpleaudioengine. As the name implies, a simple sound playback engine.
I don't list all the interfaces for this class, but at least you need to know the following interfaces:
virtual unsigned int playeffect (const char* FilePath, bool loop = false,float pitch = 1.0f, float pan = 0.0f, float gain = 1.0f);//Play the sound effects virtual void pauseeffect (unsigned int soundid);//Pause the sound to play virtual void resumeeffect (unsigned int soundid);// Restore the sound play to virtual void stopeffect (unsigned int soundid);//stop audio play virtual void Preloadeffect (const char* FilePath);// Preload a compressed sound file virtual void Unloadeffect (const char* FilePath);//unload the internal loaded sound cache
These interfaces are the interface for sound processing. For the processing of music files, this one provides two types of music that are processed separately, namely background music and sound effects. In general, background music plays longer than sound. The difference between the background music and the sound is that the background music can only play one at a time, while the sound may be multiple. And in Win32, there is currently no pre-loading of background music in cocos. Therefore, the individual feel that the background music can also be classified as a sound category.
In the test, so do we, for background music loading is also by preloading the sound file.
OK, let's take a look at the specific operation, this time first look at the source of my test:
SimpleAudioEngineTest.h:
#ifndef __simple_audio_engine_test_h__#define __simple_audio_engine_test_h__#include "cocos2d.h" #include " SimpleAudioEngine.h "<span style=" White-space:pre "></span>//contains sound engine header files Using_ns_cc;using namespace Cocosdenshion;<span style= "White-space:pre" ></span>//use the sound engine's namespace class Simpleaudioenginetest:p ublic Layer{public:simpleaudioenginetest (); static Scene *createscene (); virtual bool init (); Create_func (simpleaudioenginetest); virtual void OnEnter (); <span style= "White-space:pre" ></span>// Override the OnEnter method virtual void OnExit (); <span style= "White-space:pre" ></span>//override OnExit Method private: Simpleaudioengine *_engine;<span style= "White-space:pre" ></span>//sound engine single pointer unsigned int _audioid;< Span style= "White-space:pre" ></span>//sound file Idbool _loop;<span style= "White-space:pre" ></span> Loop play}; #endif
SimpleAudioEngineTest.cpp:
#include "SimpleAudioEngineTest.h" #include "SoundPlayerTest.h" <span style= "White-space:pre" ></span>// A header file containing the second Test to jump to the scene simpleaudioenginetest::simpleaudioenginetest () {//variable initialization _engine = Nullptr;_audioid = 0;_loop = false;} Scene *simpleaudioenginetest::createscene () {Auto scene = Scene::create (); Auto layer = Simpleaudioenginetest::create () ; Scene->addchild (layer); return scene;} BOOL Simpleaudioenginetest::init () {if (! Layer::init ()) {return false;} Auto visiblesize = Director::getinstance ()->getvisiblesize ();//Current Test label description Auto Test_label = Label:: Createwithsystemfont ("Simpleaudioengine Test", "", ","), Test_label->setposition (VEC2 (VISIBLESIZE.WIDTH/2, Visiblesize.height-test_label->getcontentsize ()); This->addchild (Test_label);//Playauto Play_Item = Menuitemfont::create ("Play", [&] (Ref *sender) {_audioid = _engine->playeffect ("Music/background.mp3", _loop) ;//When the entry is clicked, call the method that plays the sound effect, return a file ID}); Play_item->setposition (VEC2 (-VISIBLESIZE.WIDTH/4, Visiblesize.height /4));//stopauto Stop_item = Menuitemfont::create ("Stop", [&] (Ref *sender) {if (_audioid! = 0) {_engine-> Stopeffect (_audioid);//When the entry is clicked, the call stops playing the sound method, the parameter is music file Id_audioid = 0;}}); Stop_item->setposition (VEC2 (VISIBLESIZE.WIDTH/4, VISIBLESIZE.HEIGHT/4));//pauseauto Pause_Item = MenuItemFont:: Create ("Pause", [&] (Ref *sender) {if (_audioid! = 0) {_engine->pauseeffect (_audioid); <span style= " Font-family:simsun; " When the >//entry is clicked, the call pauses the sound method, the parameter is the music file Id</span>}); Pause_item->setposition (VEC2 (-VISIBLESIZE.WIDTH/4, 0))//resumeauto Resume_item = menuitemfont::create ("Resume" , [&] (Ref *sender) {if (_audioid! = 0) {_engine->resumeeffect (_audioid); <span style= "Font-family:simsun;" When the >//entry is clicked, the call resumes the playback sound method, the parameter is the music file Id</span>}); Resume_item->setposition (VEC2 (VISIBLESIZE.WIDTH/4, 0));//The second Test jump tag Auto enternexttest = Menuitemlabel::create ( Label::createwithsystemfont ("Click here Enter Next Test", "", ","), [] (Ref *sender) {director::getinstance () Replacescene (SoundplayeRtest::createscene ());}); Enternexttest->setposition (Vec2 (0,-VISIBLESIZE.HEIGHT/4)); auto menu = Menu::create (Play_item, Stop_item, Pause_ Item, Resume_item, Enternexttest, NULL); AddChild (menu, ten); return true;} void Simpleaudioenginetest::onenter () {layer::onenter ();//sound engine initialization _engine = Simpleaudioengine::getinstance ();// Pre-load sound file _engine->preloadeffect ("Music/background.mp3"); Cclog ("OnEnter ..."); void Simpleaudioenginetest::onexit () {if (_engine) {_engine->unloadeffect ("Music/background.mp3");//Clear internal sound file cache} Layer::onexit ();}
OK, let's take a look at Test two.
Test two will use another sound engine, this class is called Audioengine. It's another sound playback engine that comes out after 3.x, a bit more powerful than the first sound engine is the ability to control the playback progress of the sound, and it also achieves the control of the volume that is not implemented on the Win32 platform. Let's take a look at the interfaces that need to be understood:
static int play2d (const std::string& FilePath, BOOL loop = False, float volume = 1.0f, const audioprofile *profile = n ULLPTR)///Play music file, return music file idstatic void setvolume (int audioid, float volume);//set volume size static void pause (int audioid);// Pauses playback of music by specifying the music file id static void resume (int audioid); Resume playing music by specifying the music file id static void stop (int audioid); Stop playing music by specifying the music file id static void setfinishcallback (int audioid, const std::function<void (int,const std::string&) >& callback)///music file playback completed call the specified function static void preload (const std::string& FilePath);//Pre-load music file to internal cache static void Uncache (const std::string& FilePath);//clear its internal cache by specifying a file
These are the interfaces that test two needs to understand. For the control of the sound volume, we also need to add a slider to control the UI.
OK, now let's look at the reference code I've implemented:
SoundPlayerTest.h:
#ifndef __sound_player_test_h__#define __sound_player_test_h__#include "cocos2d.h" #include "AudioEngine.h"// Introduction of the Sound engine header file # include "ui\cocosgui.h" <span style= "white-space:pre" ></span>//ui Control header file using_ns_cc;using namespace experimental;//use the sound Engine namespace using namespace Ui;<span style= "White-space:pre" ></span> // Use the UI namespace class Soundplayertest:p ublic layer{public:soundplayertest (); static Scene *createscene (); virtual bool init (); Create_func (soundplayertest); virtual void onEnter (); virtual void OnExit ();p rivate:int _audioid;bool _loop;}; #endif
SoundPlayerTest.cpp:
#include "SoundPlayerTest.h" soundplayertest::soundplayertest () {//variable initialization _audioid = audioengine::invalid_audio_id;// This value is an initial value in Audioengine, which is -1_loop = false;} Scene *soundplayertest::createscene () {Auto scene = Scene::create (); Auto layer = Soundplayertest::create ();scene-> AddChild (layer); return scene;} BOOL Soundplayertest::init () {if (! Layer::init ()) {return false;} Auto visiblesize = Director::getinstance ()->getvisiblesize ();//Current Test label description Auto Test_label = Label:: Createwithsystemfont ("Sound Player Test", "" "," Test_label->setposition "), VEC2 (VISIBLESIZE.WIDTH/2, Visiblesize.height-test_label->getcontentsize ()); This->addchild (Test_label);//Playauto Play_Item = Menuitemfont::create ("Play", [&] (Ref *sender) {if (_audioid = = audioengine::invalid_audio_id) {_audioid = Audioengine::p lay2d ("Music/background.mp3", _loop);//Play Music file}if (_audioid! = audioengine::invalid_audio_id) { Audioengine::setfinishcallback (_audioid, [&] (int id, const std::string &filepath) {_audioid = Audioengine::invalid_audio_id; When playback is complete, initialize the sound file ID});}); Play_item->setposition (VEC2 (-VISIBLESIZE.WIDTH/4, VISIBLESIZE.HEIGHT/4));//stopauto Stop_Item = MenuItemFont:: Create ("Stop", [&] (Ref *sender) {if (_audioid! = audioengine::invalid_audio_id) {audioengine::stop (_audioid);< Span style= "White-space:pre" ></span>//stop playing music file _audioid = audioengine::invalid_audio_id;}); Stop_item->setposition (VEC2 (VISIBLESIZE.WIDTH/4, VISIBLESIZE.HEIGHT/4));//pauseauto Pause_Item = MenuItemFont:: Create ("Pause", [&] (Ref *sender) {if (_audioid! = audioengine::invalid_audio_id) {audioengine::p ause (_audioid);// Pause music File}}); Pause_item->setposition (VEC2 (-VISIBLESIZE.WIDTH/4, 0))//resumeauto Resume_item = menuitemfont::create ("Resume" , [&] (Ref *sender) {if (_audioid! = audioengine::invalid_audio_id) {audioengine::resume (_audioid);//Resume playing music file}}); Resume_item->setposition (VEC2 (VISIBLESIZE.WIDTH/4, 0)); auto menu = Menu::create (Play_item, Stop_item, Pause_Item, Resume_item, NULL); aDdchild (menu,10);//Initialize the control volume slider UISlider *slider = slider::create (); Slider->loadbartexture ("cocosui/ Slidertrack.png ")///slider background texture slider->loadslidballtextures (" cocosui/sliderthumb.png "," Cocosui/sliderthumb.png " )///sliding button texture, first for normal, second for being clicked Slider->loadprogressbartexture ("Cocosui/sliderprogress.png");//Progress Texture slider-> SetPosition (VEC2 (VISIBLESIZE.WIDTH/2)); Slider->setscale (1.5f); slider->setpercent (+); <span style= "White-space:pre" ></span>slider->addeventlistener ([&] (Ref *sender,slider::eventtype type) {Auto S = Dynamic_cast<slider*> (sender), auto Volum = 1.0f * s->getpercent ()/s->getmaxpercent ();//Calculate the volume value, the value of the volume should be: 0~ 1 between if (_audioid! = audioengine::invalid_audio_id) {audioengine::setvolume (_audioid, Volum);}}); AddChild (slider); return true;} void Soundplayertest::onenter () {layer::onenter ();//Sound engine initialization audioengine::lazyinit ();//load Sound file Audioengine::p Reload ( "Music/background.mp3"); Cclog ("OnEnter ..."); void Soundplayertest::onexit () {if (_audioid! = Audioengine::invalid_audio_id) {Audioengine::uncache ("Music/background.mp3");//clear the cache of music files}layer::onexit ();}
Well, that's what the test is about. Note that my resource files here need to be placed in the resource folder because the resource's default working directory is here. I created the music folder in resource, where all the sound resource files are placed, and the creation of a Cocosui folder is a texture file that places all the UI-related controls, as shown in:
These resources can be found in the testcpp in the source code package.
OK, finally let's look at the results of the operation ~ (although the voice can not hear, but feel the ha ~)
Well, if you want to know something about sound, you can go to the official example or the interface provided in it. The content of the sound is discussed here ~ the next article about the self-updating interface in node nodes. In the game development but occupies an important position!
COCOS2DX Learning Path----11th (handling of sound)