How to Add Media Controller on Vlc Android Programatically

How to Add Media Controller on Vlc Android Programatically

I want to to add the media controller on VLC player android integration but i didn't find any option to do that i am sharing the code -

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.otherformat);

    load = (ProgressBar) this.findViewById(R.id.load);
    intent = getIntent();
    load.setVisibility(View.VISIBLE);
    handler = new Handler();

    mFilePath ="";

    Log.e(TAG, "Playing: " + mFilePath);
    mSurface = (SurfaceView) findViewById(R.id.surface);
    holder = mSurface.getHolder();

}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    setSize(mVideoWidth, mVideoHeight);
}

@Override
protected void onResume() {
    super.onResume();
    createPlayer(mFilePath);
}

@Override
protected void onPause() {
    super.onPause();
    releasePlayer();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    releasePlayer();
}


/**
 * Used to set size for SurfaceView
 *
 * @param width
 * @param height
 */
private void setSize(int width, int height) {
    mVideoWidth = width;
    mVideoHeight = height;
    if (mVideoWidth * mVideoHeight <= 1)
        return;

    if (holder == null || mSurface == null)
        return;

    int w = getWindow().getDecorView().getWidth();
    int h = getWindow().getDecorView().getHeight();
    boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    if (w > h && isPortrait || w < h && !isPortrait) {
        int i = w;
        w = h;
        h = i;
    }

    float videoAR = (float) mVideoWidth / (float) mVideoHeight;
    float screenAR = (float) w / (float) h;

    if (screenAR < videoAR)
        h = (int) (w / videoAR);
    else
        w = (int) (h * videoAR);

    holder.setFixedSize(mVideoWidth, mVideoHeight);
    ViewGroup.LayoutParams lp = mSurface.getLayoutParams();
    lp.width = w;
    lp.height = h;
    mSurface.setLayoutParams(lp);
    mSurface.invalidate();
}

/**
 * Creates MediaPlayer and plays video
 *
 * @param media
 */
private void createPlayer(String media) {
    releasePlayer();
    try {
        if (media.length() > 0) {
            Toast toast = Toast.makeText(this, media, Toast.LENGTH_LONG);
            toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0,
                    0);
            //toast.show();
        }
        // Create LibVLC
        // TODO: make this more robust, and sync with audio demo
        ArrayList<String> options = new ArrayList<String>();
        //options.add("--subsdec-encoding <encoding>");
        options.add("--aout=opensles");
        options.add("--audio-time-stretch"); // time stretching
        options.add("-vvv"); // verbosity
        libvlc = new LibVLC(this, options);
        holder.setKeepScreenOn(true);
        // Creating media player
        mMediaPlayer = new MediaPlayer(libvlc);
        mMediaPlayer.setEventListener(mPlayerListener);
        mMediaPlayer.setVideoTrackEnabled(true);
        // Seting up video output
        final IVLCVout vout = mMediaPlayer.getVLCVout();
        vout.setVideoView(mSurface);
        //vout.setSubtitlesView(mSurfaceSubtitles);
        vout.addCallback(this);
        vout.attachViews();
        Media m = new Media(libvlc, Uri.parse(media));
        mMediaPlayer.setMedia(m);
        mMediaPlayer.play();

        ////////////////////////////////////////////////
       /*  //mController = new MediaController(this);
        mController = (MediaController)findViewById(R.id.mediaController);
        mController.setVisibility(View.VISIBLE);
        mController.setAnchorView(mSurface);
        mController.show(0);*/


        /*mController = new MediaController(this);
        mController.setAnchorView(mSurface);
        handler.post(new Runnable() {

            public void run() {
                mController.show();
            }
        });*/


    } catch (Exception e) {

        Log.e("Err", e.getMessage()+"");

        Toast.makeText(this, "Error in creating player!"+e.getMessage(), Toast
                .LENGTH_LONG).show();
    }
}

private void releasePlayer() {
    if (libvlc == null)
        return;
    mMediaPlayer.stop();
    final IVLCVout vout = mMediaPlayer.getVLCVout();
    vout.removeCallback(this);
    vout.detachViews();
    holder = null;
    libvlc.release();
    libvlc = null;
    mVideoWidth = 0;
    mVideoHeight = 0;

}

/**
 * Registering callbacks
 */

private MediaPlayer.EventListener mPlayerListener = new MyPlayerListener(this);

@Override
public void onNewLayout(IVLCVout vout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen) {
    if (width * height == 0)
        return;
    // store video size
    mVideoWidth = width;
    mVideoHeight = height;
    setSize(mVideoWidth, mVideoHeight);
}

@Override
public void onSurfacesCreated(IVLCVout vout) {


}

@Override
public void onSurfacesDestroyed(IVLCVout vout) {

}

@Override
public void onHardwareAccelerationError(IVLCVout vlcVout) {
    Log.e(TAG, "Error with hardware acceleration");
    this.releasePlayer();
    Toast.makeText(this, "Error with hardware acceleration", Toast.LENGTH_LONG).show();
}

private static class MyPlayerListener implements MediaPlayer.EventListener {
    private WeakReference<OtherFormat> mOwner;

    public MyPlayerListener(OtherFormat owner) {
        mOwner = new WeakReference<OtherFormat>(owner);
    }

    @Override
    public void onEvent(MediaPlayer.Event event) {
        OtherFormat player = mOwner.get();

        switch (event.type) {
            case MediaPlayer.Event.EndReached:
                Log.d(TAG, "MediaPlayerEndReached");
                player.releasePlayer();
                break;
            case MediaPlayer.Event.Playing:
                load.setVisibility(View.GONE);
                break;
            case MediaPlayer.Event.Paused:
            case MediaPlayer.Event.Buffering:
                float percent = event.getBuffering(); /* from 0.0f to 100f */
                Log.e("Percent><><",""+percent);
               break;
            case MediaPlayer.Event.Stopped:
                default:
                break;
        }
    }
}}

XML for this activity -

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android=""
    xmlns:tools=""
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <SurfaceView
        android:id="@+id/surface"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center" />


    <ProgressBar
        android:id="@+id/load"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:visibility="visible"
        android:layout_gravity="center"
        />


    <MediaController
        android:id="@+id/mediaController"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" >
    </MediaController>


</FrameLayout>

By this code mediacontrollers not showing please help me how to show media controllers for pause, play and seekbar for video position in surfaceview of vlc media player.

2 Answers

I had the same issue and have found a solution. Sure, it's too late for answer, but maybe I will save some time to someone.

To add default media control you need to implement it in following way

  1. remove MediaController from layout and add some container for media control to to your activity (it will be added programmatically).

    <FrameLayout
        android:id="@+id/video_surface_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:foregroundGravity="clip_horizontal|clip_vertical"
        tools:ignore="true">

        <SurfaceView
            android:id="@+id/surface"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

    </FrameLayout>
  1. add controller init to onStart activity or to onCreate

    import android.widget.MediaController;

    private MediaController controller;

    @Override
    protected void onStart() {
        super.onStart();
        ....
        controller = new MediaController(this);
        controller.setMediaPlayer(findViewByid(R.id.video_surface_frame));
        controller.setAnchorView(mVideoSurfaceFrame);
        mVideoSurfaceFrame.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
             controller.show(10000);
           }
        });
    }

  1. to define playerInterface, you need to implement the MediaController.MediaPlayerControl interface like this

    private MediaController.MediaPlayerControl playerInterface = new MediaController.MediaPlayerControl() {
        public int getBufferPercentage() {
            return 0;
        }

        public int getCurrentPosition() {
            float pos = mLibVlc.getPosition();
            return (int)(pos * getDuration());
        }

        public int getDuration() {
            return (int)mLibVlc.getLength();
        }

        public boolean isPlaying() {
            return mLibVlc.isPlaying();
        }

        public void pause() {
            mLibVlc.pause();
        }

        public void seekTo(int pos) {
            mLibVlc.setPosition((float)pos / getDuration());
        }

        public void start() {
           mLibVlc.play();
        }

        public boolean canPause() {
            return true;
        }

        public boolean canSeekBackward() {
            return true;
        }

        public boolean canSeekForward() {
            return true;
        }

        @Override
        public int getAudioSessionId() {
            return 0;
        }
    };

  1. launch your app and tap on video. You will see default media control and it will hide in 10 sec

Good luck!

Link to VideoLan sample on github:

1

public class Show_Array extends AppCompatActivity implements IVLCVout.Callback {

private TextView container_extension;
private String stream_typee,stream_idd,container_extensionn ;
private String SAMPLE_URL = "";
public int mHeight;
public int mWidth;
private SurfaceView mVideoSurface = null;
private FrameLayout sdk;
private IVLCVout vlcVout;
private LibVLC mLibVlc = null;
private MediaPlayer mMediaPlayer = null;
private int flag = 0;
private ImageButton Resize;
private Media media;
private ArrayList<String> args;
private SurfaceHolder mSurfaceHolderVideo;
private MediaController controller;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.show__array);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    //Referances
    Resize = findViewById(R.id.Resize);
    mVideoSurface =  findViewById(R.id.video_surface);


    stream_typee = getIntent().getExtras().getString("stream_type");
    stream_idd = getIntent().getExtras().getString("stream_id");
    container_extensionn = getIntent().getExtras().getString("container_extension");

    args = new ArrayList<>();
    args.add("-vvv");
    mLibVlc = new LibVLC(this, args);
    mMediaPlayer = new MediaPlayer(mLibVlc);
    vlcVout = mMediaPlayer.getVLCVout();
    sdk = findViewById(R.id.sdk);


    Resize_video();
    setup_url();

    controller = new MediaController(this);
    controller.setMediaPlayer(playerInterface);
    controller.setAnchorView(mVideoSurface);
    mVideoSurface.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            controller.show(10000);
        }
    });

}

@Override
protected void onDestroy() {
    super.onDestroy();
    mMediaPlayer.release();
    mLibVlc.release();
}

void Resize_video()
{
    DisplayMetrics displayMetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    mHeight = displayMetrics.heightPixels;
    mWidth = displayMetrics.widthPixels;
    Resize.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            flag+=1;
            int width = 1000;
            int height = 560;

            if(flag%2!=0) {

                LinearLayout.LayoutParams myImageLayout = new LinearLayout.LayoutParams(width, height);
                myImageLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
                sdk.setLayoutParams(myImageLayout);
                vlcVout.setWindowSize(width,height);

            }
            else
            {
                LinearLayout.LayoutParams myImageLayout = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                myImageLayout.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
                sdk.setLayoutParams(myImageLayout);
                vlcVout.setWindowSize(mWidth,mHeight);

            }
        }
    });
}
void setup_url()
{
    //TextView
    container_extension = findViewById(R.id.URL);
    if (stream_typee.equals("live"))
    {
        SAMPLE_URL = ""+stream_typee+"/webserver/6tE@BzW73@sX/"+stream_idd+".ts";
        container_extension.setText( SAMPLE_URL);
    }else
    {
        SAMPLE_URL = ""+stream_typee+"/webserver/6tE@BzW73@sX/"+stream_idd+"."+container_extensionn;
        container_extension.setText( SAMPLE_URL);

    }
}

@Override
protected void onStart() {
    super.onStart();
    vlcVout.setWindowSize(mWidth,mHeight);
    vlcVout.setVideoView(mVideoSurface);
    vlcVout.attachViews();
    mMediaPlayer.getVLCVout().addCallback(this);
    if(!SAMPLE_URL.isEmpty()) {
         media = new Media(mLibVlc, Uri.parse(SAMPLE_URL));
        mMediaPlayer.setMedia(media);
        media.release();
        mMediaPlayer.play();


    }else
    {
        Toast.makeText(getApplicationContext(),"URL EMPTY",Toast.LENGTH_LONG).show();
    }


}

@Override
protected void onStop() {
    super.onStop();

    mMediaPlayer.stop();
    mMediaPlayer.getVLCVout().detachViews();
    mMediaPlayer.getVLCVout().removeCallback(this);


}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
@Override
public void onNewLayout(IVLCVout vlcVout, int width, int height, int visibleWidth, int visibleHeight, int sarNum, int sarDen)
{ }

@Override
public void onSurfacesCreated(IVLCVout vlcVout) {
}

@Override
public void onSurfacesDestroyed(IVLCVout vlcVout) {
}
private MediaController.MediaPlayerControl playerInterface = new MediaController.MediaPlayerControl() {
    public int getBufferPercentage() {
        return 0;
    }

    public int getCurrentPosition() {
        float pos = mMediaPlayer.getPosition();
        return (int)(pos * getDuration());
    }

    public int getDuration() {
        return (int)mMediaPlayer.getLength();
    }

    public boolean isPlaying() {
        return mMediaPlayer.isPlaying();
    }

    public void pause() {
        mMediaPlayer.pause();
    }

    public void seekTo(int pos) {
        mMediaPlayer.setPosition((float)pos / getDuration());
    }

    public void start() {
        mMediaPlayer.play();
    }

    public boolean canPause() {
        return true;
    }

    public boolean canSeekBackward() {
        return true;
    }

    public boolean canSeekForward() {
        return true;
    }

    @Override
    public int getAudioSessionId() {
        return 0;
    }
};

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.