Muting a video in a VideoView
If you are coding in kotlin, Just use this line of code
videoView.setOnPreparedListener { video->
video.setVolume(0f,0f)
}
put this code in oncreate() and also in onresume() for handle video view in better way...
VideoView videoview = (VideoView) findViewById(R.id.videoview);
videoview.setVideoPath(videopath);
videoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.setVolume(0f, 0f);
mp.setLooping(true);
}
});
videoview.start();
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.