androidkeymediavolumerecorder

can't record audio via volume up button


im trying to create and app with a recording an audio and playing it. it currently has 2 buttons - 1 for recording and 1 for playing the last recorded sound. when im pressing the recording button it works perfect.

then, i tried to make it record by capturing the volume up button click.(wanted to make it record as long as the button is pressed).

when i try to record from the volume up button it throws me and IllegalStateException.

this is how i handle the click action on the volume up:

public boolean onKeyDown(int keyCode, KeyEvent event) {
 switch(keyCode){
   case KeyEvent.KEYCODE_VOLUME_UP:
     player.startRecording();
     return true;
 }
 return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch(keyCode){
    case KeyEvent.KEYCODE_VOLUME_UP:
            player.stopRecording();
            return true;
        }

    return super.onKeyUp(keyCode, event);
}

thx in advance and sorry for the bad english


Solution

  • When you hold volume up button, it will fire onKeyDown event continuesly..in each such call it invokes player.stopRecording();.. this may cause problem,,,just try below logic...

    public class MainActivity extends ActionBarActivity {
    
    int keyStatus=0;//public variable, 0=key released,1=key pressed
    
    //
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
         switch(keyCode){
           case KeyEvent.KEYCODE_VOLUME_UP:
             //player.startRecording();
               if(keyStatus==0){
                   keyStatus=1;//setting this to 1 to ensure that this block is called only once during the key pressed state
                   Log.d("msg", "startRecording()");
               }
             return true;
         }
         return super.onKeyDown(keyCode, event);
        }
    @Override
        public boolean onKeyUp(int keyCode, KeyEvent event) {
            switch(keyCode){
            case KeyEvent.KEYCODE_VOLUME_UP:
                   Log.d("msg", "stopRecording()");
                   keyStatus=0;//reset keyStatus on key up event.
                    return true;
                }
    
            return super.onKeyUp(keyCode, event);
        }
    
    //