Controlling sound with device volume key [solved]

Controlling sound with device volume key [solved]
0.0 0


Hi All,
I know this has been already talked about but I found no real solution to this issue and I am in need of pointers or directions to solve this.

on Android, the volume keys do not work at all.

I’ve read that implementing OnKeyPressed(const Osp::Ui::Control& source, Osp::Ui::KeyCode keyCode) is the possible solution, but that funcion is not available in CCApplication_android.h so I am not sure how to override such method…

any ideas?

Thanks a lot,


I finally solved this by adding this to the Activity:

    public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
        boolean result = false;
        Log.d("cocos activity", "" + event);
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            float newVolume = backgroundMusicPlayer.getBackgroundVolume() - 0.1f;
            if (newVolume <= 0.0f) {
                newVolume = 0.0f;


            result = true;
        else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
            float newVolume = backgroundMusicPlayer.getBackgroundVolume() + 0.1f;
            if (newVolume >= 1.0f) {
                newVolume = 1.0f;

            result = true;
        return result;


But, if you play music, you are able automatically increase/decrease music and sfx volume by volume keys.

So why you need make it manually?


because it was not working?


I have written like this [[]]
i change from cocos2d to coscos2d-x

// Create your audio engine
[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"music.mp3"];

// Create the slider
CCControlSlider *slider = [CCControlSlider sliderWithBackgroundFile:@"sliderTrack.png" progressFile:@"sliderProgress.png" thumbFile:@"sliderThumb.png"];
slider.minimumValue = 0.0f; // Sets the min value of range
slider.maximumValue = 1.0f; // Sets the max value of range

// When the value of the slider will change, the given selector will be call
[slider addTarget:self action:@selector(valueChanged:) forControlEvents:CCControlEventValueChanged];

[self addChild:slider]; 


- (void)valueChanged:(CCControlSlider *)sender
   // Change volume of your sounds
   [[SimpleAudioEngine sharedEngine] setEffectsVolume:sender.value];
   [[SimpleAudioEngine sharedEngine] setBackgroundMusicVolume:sender.value];



slider= CCControlSlider::create("sounds/sound_bar_boder.png","sounds/sound_slide_bar.png","sounds/sound_slide_bt.png");


slider->setPosition(ccp(size.width/2, size.height/2));


void SoundScene::actionSlider(CCObject* pSender,unsigned int controlEvent)
    CCControlSlider* pSlider = (CCControlSlider*)pSender;



But i can’t control volume when i play music.Please help me fix this code.Thanks