Integrating video file in android app as app background

前端 未结 6 1430
感情败类
感情败类 2020-11-30 19:36

I need to use video as my background. First I placed the video file in drawable folder and called as background of LinearLayout in main.xml. But while running t

6条回答
  •  被撕碎了的回忆
    2020-11-30 20:11

    I have used this code for play video on surface view

    public class VideoPlayOnSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    
        private MediaPlayer mediaPlayer;
        private boolean has_started = false;
    
        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        public VideoPlayOnSurfaceView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
            init();
        }
    
        public VideoPlayOnSurfaceView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            init();
        }
    
        public VideoPlayOnSurfaceView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public VideoPlayOnSurfaceView(Context context) {
            super(context);
            init();
        }
    
        private void init() {
            mediaPlayer = new MediaPlayer();
            getHolder().addCallback(this);
        }
    
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.small);
            try {
                if (!has_started) {
                    has_started = true;
                    mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
                }
    
                mediaPlayer.prepare();
                android.view.ViewGroup.LayoutParams lp = getLayoutParams();
                lp.height = getHeight();
                lp.width = getWidth();
    
                setLayoutParams(lp);
                mediaPlayer.setDisplay(holder);
                mediaPlayer.setLooping(true);
                mediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }
    
        @Override public void surfaceDestroyed(SurfaceHolder holder) {
            mediaPlayer.stop();
        }
    }
    

    xml file

    
    
    
            
    
    

提交回复
热议问题