1. 程式人生 > >VideoView控制音量(靜音\恢復)

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(); } }