Android音乐播放器SeekBar控制音量变化的实现

private int maxVolume, currentVolume;
private AudioManager audioManager;
private SeekBar mView_sb_play_volume = null;

**Avtivity:**

protected void onCreate(android.os.Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mView_sb_play_volume = (SeekBar) findViewById(R.id.play_volume);
        setVolume();

    };
    /***
     * 设置音量
     */
    private void setVolume() {
        myRegisterReceiver();//注册同步更新的广播  
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);  //获取系统最大音量
        mView_sb_play_volume.setMax(maxVolume);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);  //获取当前值  
        mView_sb_play_volume.setProgress(currentVolume);
        mView_sb_play_volume.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                    boolean fromUser) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);

            }
        });
    }
    /** 
    * 注册当音量发生变化时接收的广播 
    */  
       private void myRegisterReceiver(){  
        MyVolumeReceiver  mVolumeReceiver = new MyVolumeReceiver() ;  
           IntentFilter filter = new IntentFilter() ;  
           filter.addAction("android.media.VOLUME_CHANGED_ACTION") ;  
           registerReceiver(mVolumeReceiver, filter) ;  
       }  

       /** 
        * 处理音量变化时的界面显示 
        * @author long 
        */  
       private class MyVolumeReceiver extends BroadcastReceiver{  
           @Override  
           public void onReceive(Context context, Intent intent) {  
               //如果音量发生变化则更改seekbar的位置  
               if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){  
                //AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);  
                    currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) ;// 当前的媒体音量  
                   mView_sb_play_volume.setProgress(currentVolume) ;  
               }  
           }  
       }  

你可能感兴趣的:(Android音乐播放器SeekBar控制音量变化的实现)