1.用AudioManager調聲音 1_得到當前音量和最大音量 2_拖動的時候改變音量 3_靜音和非靜音 2.手指在屏幕上下滑動實現聲音大小變化 3.監聽按手機聲音健改變聲音大小 ...
1.用AudioManager調聲音
1_得到當前音量和最大音量
//關於設置音量 private int currentVolume;//當前音量值 private int currentMaxVolume;//當前最大音量 private AudioManager am; am = (AudioManager) getSystemService(AUDIO_SERVICE); currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC); currentMaxVolume = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
2_拖動的時候改變音量
voice_seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onStopTrackingTouch(SeekBar seekBar) { sendDelayedHideControlPlayerMessage(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { removeDelayedHideControlPlayerMessage(); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { if(fromUser){ updateVolume(progress); } } }); /** * 修改音量範圍0~15 * @param progress2 */ protected void updateVolume(int volume) { am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0); voice_seekBar.setProgress(volume); currentVolume = volume; }
3_靜音和非靜音
case R.id.btn_voice: isMute = !isMute; updateVolume(currentVolume); break; /** * 修改音量範圍0~15 * @param progress2 */ protected void updateVolume(int volume) { if(isMute){ am.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0); voice_seekBar.setProgress(0); }else{ am.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0); voice_seekBar.setProgress(volume); } currentVolume = volume; }
2.手指在屏幕上下滑動實現聲音大小變化
private float startY; /** * 滑動的區域 */ private float touchRang; /** * 當前的音量 */ private int mVol; @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN://手指按下屏幕 //1.記錄相關的值 startY = event.getY(); touchRang =Math.min(screenWidth, screenHeight);//screenHeight mVol = am.getStreamVolume(AudioManager.STREAM_MUSIC); handler.removeMessages(HIDE_MEDIACONTROL); break; case MotionEvent.ACTION_MOVE://手指在屏幕上移動 //2.來到結束的坐標 float endY = event.getY(); //3.計算偏移量 float distanceY = startY - endY; //要改變的聲音 = (滑動的距離 / 總距離)*最大音量 float delta = (distanceY/touchRang)*maxVolume; //最終聲音 = 原來的聲音 + 要改變的聲音 float volum e = Math.min(Math.max(mVol+delta,0),maxVolume); if(delta != 0){ updatavolumeProgress((int) volume); } // startY = event.getY(); break; case MotionEvent.ACTION_UP://手指離開屏幕 handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROL,5000); break; } return super.onTouchEvent(event); }
3.監聽按手機聲音健改變聲音大小
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){ currentVolume--; updatavolumeProgress(currentVolume); handler.removeMessages(HIDE_MEDIACONTROL); handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROL, 5000); return true; }else if(keyCode ==KeyEvent.KEYCODE_VOLUME_UP){ currentVolume++; updatavolumeProgress(currentVolume); handler.removeMessages(HIDE_MEDIACONTROL); handler.sendEmptyMessageDelayed(HIDE_MEDIACONTROL, 5000); return true; } return super.onKeyDown(keyCode, event); }