android-----音乐播放器的音量控制功能(开发)

一、布局文件

在RelativeLayout布局里设置一个ImageButton,点击其弹出一个SeekBar(用于音量调节),

再在其下面嵌套一个RelativeLayout,里面包含两个ImageView组件、一个SeekBar组件。

此外, anim---push_up_in.xml 是一个动画集合,包括interpolator负责控制动画的变化速度;translate即平移动画以及一个alpha即透明度渐变的动画。

使用动画,会让你在调节音量时按下滑块与松开滑块有不一样的效果。

二、代码实现

关键代码

//音频面板的显示和隐藏
    private void voicePanelAnimation() {
        if (llPlayerVoice.getVisibility() == View.GONE)
        {
            llPlayerVoice.startAnimation(showVoicePanelAnimation);
            llPlayerVoice.setVisibility(View.VISIBLE);
        }
        else {
            llPlayerVoice.startAnimation(hiddenVoicePanelAnimation);
            llPlayerVoice.setVisibility(View.GONE);
        }
    }
    
private OnClickListener listener = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
            case R.id.btnPlayerVoice:
                voicePanelAnimation();
                break;
            default:
                break;
            }
        }
    };
    
    private OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
        
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub    
        }
        
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // TODO Auto-generated method stub
            
        }
        
        //当拖动条的滑块位置发生改变时触发该方法
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // TODO Auto-generated method stub
            
            if (seekBar.getId() == R.id.sbPlayerVoice)
            {
                currentVolume = progress;
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
            }
        }
    };

    //隐藏系统音量条
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        switch (keyCode)
        {
        case KeyEvent.KEYCODE_VOLUME_UP:
            currentVolume += 2;
            if(currentVolume >= audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)){
                currentVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            }
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            sbPlayerVoice.setProgress(currentVolume);
        case KeyEvent.KEYCODE_VOLUME_DOWN:
            currentVolume -= 2;
            if(currentVolume < 0) {
                currentVolume = 0;
            }
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
            sbPlayerVoice.setProgress(currentVolume);
            return true;
        default:
            break;
    }


android-----音乐播放器的音量控制功能(开发)_第1张图片




你可能感兴趣的:(android相关)