android系统声音调节

时间:2021-06-12 23:59:34

系统声音调节

1.调节播放器声音,不受系统声音限制

2.拦截系统声音,控制用户调节。(用户无法控制系统声音)

首先获取系统声音等:

//声音管理器
mAudioManager = (AudioManager)mOuterContext.getSystemService(Context.AUDIO_SERVICE);
//获取系统的最大声音
        maxVolumn = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//获取系统当前的声音
                systemVolum = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//注册监听系统声音广播
private void registerVolumeChangeReceiver() {
        mSettingsContentObserver = new SettingsContentObserver(mOuterContext, new Handler());
        MyApplication.application.getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver);
    }
//取消注册监听系统声音广播
    private void unregisterVolumeChangeReceiver(){
        if(mSettingsContentObserver != null) {
            MyApplication.application.getContentResolver().unregisterContentObserver(mSettingsContentObserver);
            mSettingsContentObserver = null;
        }
    }

下面是具体的广播内容:

public class SettingsContentObserver extends ContentObserver {
        Context context;

        public SettingsContentObserver(Context c, Handler handler) {
            super(handler);
            context = c;
        }

        @Override
        public boolean deliverSelfNotifications() {
            return super.deliverSelfNotifications();
        }

        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            if(!isFullScreen && !startChange){
                LogUtils.i("guest :volumChange");
                mHandler.sendEmptyMessageDelayed(18,30);
            }
        }
    }

发送出消息后可以控制调节系统声音:

                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,maxVolumn,0);

MediaPlayer调节系统声音:

 myMp.setVolume(0.0f, 0.0f);//设置左右声道为0
//设置为当前系统声音
myMp.setVolume(getSystemVolumn(mOuterContext), getSystemVolumn(mOuterContext));

获取系统声音的方法:

public float getSystemVolumn(Context context) {
        if (context != null) {
            try {
                return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC) * 1.0F / maxVolumn;
            } catch (UnsupportedOperationException e) {

            }
        }
        return 0.5F;
    }