【转载】cocos2dx 3.x 声音播放、音量调节
1. playBackgroudMusic()
playBackgroudMusic 只适合播放持续时间比较长的声音文件,比如背景音乐。
- bool PlayMusic::init()
- {
- if ( !Layer::init() )
- {
- return false;
- }
- bool bRet = false;
- do{
- CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("sky_city.mp3",true);
- bRet = true;
- }while(0);
- return bRet;
- }
2. playEffect()
playEffect 适合播放战斗的打斗声音、技能释放的声音。
- bool PlayMusic::init()
- {
- if ( !Layer::init() )
- {
- return false;
- }
- bool bRet = false;
- do{
- //CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("sky_city.mp3",true);
- CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect("error.wav");
- bRet = true;
- }while(0);
- return bRet;
- }
3. 圆形音量按钮 ControlPotentiometer
一个圆形音量按钮由底座、进度条、控制按钮三部分组成。创建好音量按钮之后,它具备调节音量的功能,只有鼠标放在控制按钮上拖到一次,进度条就会改变显示范围,当然如果想控制音量,还需要加入监听事件。
- bool PlayMusic::init()
- {
- if ( !Layer::init() )
- {
- return false;
- }
- ControlPotentiometer* potentiometer = ControlPotentiometer::create("potentiometerTrack.png","potentiometerProgress.png","potentiometerButton.png");
- potentiometer->setPosition(Point(200,200));
- //监听进度值改变事件
- potentiometer->addTargetWithActionForControlEvents(this,cccontrol_selector(PlayMusic::onValueChange),Control::EventType::VALUE_CHANGED);
- this->addChild(potentiometer);
- return true;
- }
- void PlayMusic::onValueChange(Ref* psender,Control::EventType event)
- {
- ControlPotentiometer* potentiometer = (ControlPotentiometer*)psender;
- String* valueStr = String::createWithFormat("%f",potentiometer->getValue());
- log(valueStr->getCString());
- }
4. 音量控制按钮
ControlSlider 也是有底部、进度条、控制按钮三部分组成。用法和ControlPotentiometer几乎一样。
- ControlSlider* slider = ControlSlider::create("background.png","progress.png","sliderThumb.png");
- slider->setPosition(ccp(300,200));
- //设置滑动条的范围
- slider->setMinimumValue(0);
- slider->setMaximumValue(1000);
- //设置滑动条当前值
- slider->setValue(300);
- slider->addTargetWithActionForControlEvents(this,cccontrol_selector(PlayMusic::sliderChange),Control::EventType::VALUE_CHANGED);
- this->addChild(slider);
- void PlayMusic::sliderChange(Ref* psender,Control::EventType event)
- {
- ControlSlider* slider = (ControlSlider*)psender;
- String* valueStr = String::createWithFormat("%f",slider->getValue());
- log(valueStr->getCString());
- }