Search code examples
javaandroidvideo-streamingaudio-streaming

Muting a video in a VideoView


I'm playing a video (from youtube) using a VideoView, like this:

VideoView video = (ViewView) this.findViewById(R.id.youtube_video);
MediaController controllers = new MediaController(this);
controllers.setAnchorView(video);
video.setMediaController(controllers);

video.setVideoURI(videoUri);
video.start()

I would like to be able to mute the video, but so far the only thing I found is:

AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

Which works fine in that the video is muted, but the problem is that all of the streamed music is muted, and if there's another video (or audio) which I want to play it's also muted.

Is there a way to just target the specific stream to be muted?
Thanks.


Solution

  • After digging into every possible source of information I managed to find, I came up with the following solution and thought it might benefit others in the future:

    public class Player extends VideoView implements OnPreparedListener, OnCompletionListener, OnErrorListener {
        private MediaPlayer mediaPlayer;
    
        public Player(Context context, AttributeSet attributes) {
            super(context, attributes);
    
            this.setOnPreparedListener(this);
            this.setOnCompletionListener(this);
            this.setOnErrorListener(this);
        }
    
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            this.mediaPlayer = mediaPlayer;
        }
    
        @Override
        public boolean onError(MediaPlayer mediaPlayer, int what, int extra) { ... }
    
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) { ... }
    
        public void mute() {
            this.setVolume(0);
        }
    
        public void unmute() {
            this.setVolume(100);
        }
    
        private void setVolume(int amount) {
            final int max = 100;
            final double numerator = max - amount > 0 ? Math.log(max - amount) : 0;
            final float volume = (float) (1 - (numerator / Math.log(max)));
    
            this.mediaPlayer.setVolume(volume, volume);
        }
    }
    

    It seems to working well for me, acting just like a VideoView with mute/unmute functionality.
    It's possible to make the setVolume method public so that volume can be controlled outside of the scope of the class, but I just needed mute/unmute to be exposed.