How do use a MediaPlayer to a SurfaceView in a Fragment

﹥>﹥吖頭↗ 提交于 2019-12-08 19:53:06

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/50181565/how-do-use-a-mediaplayer-to-a-surfaceview-in-a-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!