VideoView控制音量(静音\恢复)

    /**
     * 使用AudioManager控制音量
     * @param value
     * @param context
     * //    https://github.com/lucid-lynxz/BlogSamples/blob/master/VideoViewDemo/app/src/main/java/org/lynxz/videoviewdemo/MainActivity.java
     */
    private void setVoiceVolume(float value,Context context) {
    	try {
    		AudioManager audioManager=
    		(AudioManager)context.getSystemService(Service.AUDIO_SERVICE);
	    	int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);//(最大值是15)
	        int flag = value > 0 ? -1 : 1;
	        currentVolume += flag * 0.1 * maxVolume;
	        // 对currentVolume进行限制
	        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}

    }

    	
    	
    /**
     * @param volume 音量大小
     * @param object VideoView实例
     *   ///VideoView 反射 MediaPlayer控制音量 http://blog.csdn.net/u012874222/article/details/73303264
     * 静音有效果,恢复无效
     * */
    private void setVolume(float volume,Object object) {
        try {
            Class forName = Class.forName("android.widget.VideoView");
            Field field = forName.getDeclaredField("mMediaPlayer");
            field.setAccessible(true);
            MediaPlayer mMediaPlayer = (MediaPlayer) field.get(object);
            mMediaPlayer.setVolume(volume, volume);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(Android)