如何以编程方式在 VLC android 上添加媒体控制器

Posted

技术标签:

【中文标题】如何以编程方式在 VLC android 上添加媒体控制器【英文标题】:How to add media controller on VLC android programatically 【发布时间】:2017-08-14 12:00:45 【问题描述】:

我想在 VLC 播放器 android 集成中添加媒体控制器,但我没有找到任何可以共享代码的选项 -

@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 ="http://mm2.pcslab.com/mm/7h800.mp4";

    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 -

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    >

    <SurfaceView
        android:id="@+id/surface"
        android:layout_
        android:layout_
        android:layout_gravity="center" />


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


    <MediaController
        android:id="@+id/mediaController"
        android:layout_
        android:layout_
        android:layout_alignParentBottom="true" >
    </MediaController>


</FrameLayout>

通过此代码媒体控制器未显示,请帮助我如何在 vlc 媒体播放器的表面视图中显示媒体控制器以用于暂停、播放和搜索栏的视频位置。

【问题讨论】:

【参考方案1】:

我遇到了同样的问题并找到了解决方案。 当然,现在回答为时已晚,但也许我会为某人节省一些时间。

要添加默认媒体控件,您需要通过以下方式实现它

    从布局中删除 MediaController 并将一些用于媒体控制的容器添加到您的活动中(它将以编程方式添加)。
    将控制器初始化添加到 onStart 活动或 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);
           
        );
    

    要定义playerInterface,需要像这样实现MediaController.MediaPlayerControl接口

    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;
        
    ;

    启动您的应用并点击视频。您将看到默认媒体控件,它会在 10 秒内隐藏

祝你好运!

链接到 github 上的 VideoLan 示例: https://code.videolan.org/videolan/vlc-android/blob/f3db2e4a33bf96c03056874322fb5b9304f92259/vlc-android/src/vlc/android/VLC.java

【讨论】:

糟糕的答案 :) 对于那些想要实现播放器接口的人替换 controller.setMediaPlayer(findViewByid(R.id.video_surface_frame));与控制器.setMediaPlayer(playerInterface);谢谢【参考方案2】:

公共类 Show_Array 扩展 AppCompatActivity 实现 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 = "http://uautv.ru:2095/"+stream_typee+"/webserver/6tE@BzW73@sX/"+stream_idd+".ts";
        container_extension.setText( SAMPLE_URL);
    else
    
        SAMPLE_URL = "http://uautv.ru:2095/"+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;
    
;

【讨论】:

以上是关于如何以编程方式在 VLC android 上添加媒体控制器的主要内容,如果未能解决你的问题,请参考以下文章

如何仅以编程方式在android中添加动态网格布局?

PWA:如何以编程方式触发:“添加到主屏幕”?在 iOS Safari 上

如何在android中以编程方式将铃声添加到本机应用程序联系人

如何以编程方式在 couchbase android 中添加 ssl 证书

如何在Android中以编程方式向影像添加阴影? [重复]

如何以编程方式在android中添加自定义帐户?