I want to control my MediaPlayer volume with the hardware volume keys.
First I tried it with AudioManager but had no success and also read
it's not good to use AudioManager ("And DON'T use AudioManager to set volume!"
https://stackoverflow.com/questions/5215459/android-mediaplayer-setvolume-function?rq=1)
Instead I tried it like this: https://stackoverflow.com/questions/6742174/controlling-volume-in-mediaplayer
to set the volume directly.
My code:
But my problem is: The onKeyDown events for hardware key up/down are only reached when MediaPlayer/MediaRecorder are stopped. But then I don't need them anymore.
So what can I do to access the KeyEvent.KEYCODE_VOLUME_UP/DOWN events
when the MediaPlayer/MediaRecorder are active?
First I tried it with AudioManager but had no success and also read
it's not good to use AudioManager ("And DON'T use AudioManager to set volume!"
https://stackoverflow.com/questions/5215459/android-mediaplayer-setvolume-function?rq=1)
Instead I tried it like this: https://stackoverflow.com/questions/6742174/controlling-volume-in-mediaplayer
to set the volume directly.
My code:
Code:
[USER=1021285]@override[/USER]
public boolean onKeyDown(int keyCode, KeyEvent event) {
//boolean result = true;
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
Log.d(TAG, "volume up"); //only reached if MediaPlayer/MediaRecorder are stopped
volume = volume - 0.05f;
if (volume < 0) {volume = 0f;}
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
Log.d(TAG, "volume down"); //only reached if MediaPlayer/MediaRecorder are stopped
volume = volume + 0.05f;
if (volume > 1) {volume = 1f;}
return true;
}
return false;
}
private void playAudioFile(String filename) {
block_another_play = true;
player = new MediaPlayer();
player.setVolume(volume, volume);
....
[USER=1021285]@override[/USER]
public void onPrepared(MediaPlayer player) {
//MediaController
controller.setMediaPlayer(this);
player.start();
controller.setEnabled(true);
controller.show(0);
But my problem is: The onKeyDown events for hardware key up/down are only reached when MediaPlayer/MediaRecorder are stopped. But then I don't need them anymore.
So what can I do to access the KeyEvent.KEYCODE_VOLUME_UP/DOWN events
when the MediaPlayer/MediaRecorder are active?
Last edited by a moderator: