Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do use a MediaPlayer to a SurfaceView in a Fragment

Because I want to be able to pass the MediaPlayer that plays the video around, I want to use a SurfaceView instead of a VideoView inside my fragment that plays the video.

I looked at an earlier question about how to attach the MediaPlayer to the SurfaceView. The answer to the question tells me to create two functions:

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

    getWindow().setFormat(PixelFormat.UNKNOWN);
    mPreview = (SurfaceView)findViewById(R.id.surfaceView);
    holder = mPreview.getHolder();
    holder.setFixedSize(800, 480);
    holder.addCallback(this);
    holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    mp = new MediaPlayer();
}


@Override
public void surfaceCreated(SurfaceHolder holder) {
    // TODO Auto-generated method stub
    mp.setDisplay(holder);
    play();
}

Unfortunately, I can't overwrite surfaceCreated via a Fragment because a Fragment doesn't have the method. Can I still attach MediaPlayer to a SurfaceView in a Fragment?

like image 649
Christian Avatar asked May 04 '18 18:05

Christian


1 Answers

Pass Surface View From Fragment to parent Activity using Callback Listener and then attach Media Player from activity to surface View then update Fragment Surface View, demo code , IN Fragment

      SurfaceView mPreview ;

  private MyListener mylistener=null;
  public interface MyListener extends EventListener{
     void onPassSurface(SurfaceView surfaceview);
    }

   public void setListener (MyListener listener)
     {
        mylistener = listener;
      }

     public void updateSurfaceView(SurfaceView surfaceview)
      {
                  mPreview=surfaceview;

                 }

     mPreview =  (SurfaceView)findViewById(R.id.surfaceView);

     mylistener.onPassSurface(mPreview);

IN ACTIVITY

    MyFragment  myfragment=new MyFragmment();
    myfragment.setListener(new MyFragment.MyListener)
     {
       @Override
       void onPassSurface(SurfaceView mPreview)
         {
            //attach Media Player Here or Write Method to attach
            //media player with Surface View and Call from Here

            //after attaching media player call this method
              myfragment.updateSurfaceView(mPreview);
            }
like image 166
Muhammad Hassaan Avatar answered Oct 05 '22 13:10

Muhammad Hassaan