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