Pausing MediaPlayer video and keeping screen visible - android

I was wondering if there was a way to pause the mediaplayer and keep the screen visible. What I mean by that is keep the current image on the screen as it is paused. What i've done is set up a timer that pauses the mediaplayer for a certain amount of time. As it is paused for that time I want current video to be visable. However, everytime I pause the Mediaplayer the screen goes black untill I call the Mediplayer.start() again. Is there anyway around this.
Thanks
Edit with code
public class FullImageActivity extends Activity implements SurfaceHolder.Callback, OnPreparedListener, OnErrorListener{
private static final String TAG = null;
MediaPlayer player;
SurfaceView surfaceview;
SurfaceHolder surfaceHolder;
int width;
int height;
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
Intent i = getIntent();
long id = i.getExtras().getLong("id");
path = i.getExtras().getString("videopath");
surfaceview = (SurfaceView)findViewById(R.id.surfaceview);
surfaceHolder = surfaceview.getHolder();
surfaceHolder.addCallback(this);
player = new MediaPlayer();
playVideo();
}
public void playVideo(){
try {
player.reset();
player.setOnErrorListener(this);
player.setDataSource(path);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
player.release();
Log.i(TAG, "Mediaplayer was relased");
super.onPause();
}
#Override
protected void onResume() {
playVideo();
super.onResume();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPrepared(MediaPlayer p) {
width=player.getVideoWidth();
height=player.getVideoHeight();
if (width!=0 && height!=0) {
surfaceHolder.setFixedSize(width, height);
player.start();
player.pause();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
player.start();
}
}, 3000);
}
}

Related

Android MediaPlayer with SurfaceView Fails on Prepare() Method

I am trying to build a video player using surface view and media player. My data source is an online video and I have enabled internet permission in manifest.
However, the video does not pay but throws a warning about prepare method without any hint at what the problem is like below:
W/System.err: at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1188)
at in.sashi.androidvideoplayer.MainActivity.surfaceCreated(MainActivity.java:64)
here's my code for this purpose:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private SurfaceView surfaceView;
private ImageView playIV, backIV;
private TextView videoNameTV;
private MediaPlayer mediaPlayer;
private SurfaceHolder holder;
// private static final String VIDEO_URL = "https://www.youtube.com/watch?v=vEVd0QMjCc8";
private static final String VIDEO_URL = "http://mic.duytan.edu.vn:83/FINAL.mp4";
private static final String VIDEO_NAME = "FALL HARDER | BASKETBALL MOTIVATION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
surfaceView = findViewById(R.id.surfsceView);
playIV = findViewById(R.id.playIV);
backIV = findViewById(R.id.backIV);
videoNameTV = findViewById(R.id.videoNameTV);
videoNameTV.setText(VIDEO_NAME);
backIV.setOnClickListener(this);
playIV.setOnClickListener(this);
holder = surfaceView.getHolder();
holder.addCallback(this);
surfaceView.setKeepScreenOn(true);
mediaPlayer = new MediaPlayer();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource(VIDEO_URL);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.backIV:
onBackPressed();
break;
case R.id.playIV:
if (mediaPlayer.isPlaying()){
Log.d(TAG, "Pause Clicked");
mediaPlayer.pause();
playIV.setImageResource(R.drawable.play);
} else {
Log.d(TAG, "Play Clicked");
mediaPlayer.start();
playIV.setImageResource(R.drawable.pause);
}
break;
}
}
#Override
protected void onPause() {
super.onPause();
collect();
}
private void collect() {
if (mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Can anyone help me to figure this out? Thanks.
Use mediaplayer object which is being defined globally.
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
How about this?
#Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource(VIDEO_URL);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}

Android: Video in TextureView

I came to know that we can play video in texture view. But I saw only how to play videos capturing by camera but I want to play an available video in it to perform any animations.
I have tried this code but I don't know where to place video.mp4
public class MainActivity extends Activity implements
TextureView.SurfaceTextureListener {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
TextureView textureView = (TextureView) findViewById(R.id.textureView1);
textureView.setSurfaceTextureListener(this);
}
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
int height) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setSurface(new Surface(surface));
try {
mediaPlayer.setDataSource("video.mp4");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,
int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture arg0) {
// TODO Auto-generated method stub
}
}
Please help me by giving any working code. Or if mine was correct then where to place video.mp4 in the folders.
Thanks in advance...
Place it in raw folder and try the below one and see if it helps.
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setSurface(new Surface(surface));
try {
Uri video = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.your_raw_file);
mediaPlayer.setDataSource(this, video);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Android play video in surfaceview NullPointerException

I try to play video in surfaceview. I use Fragment (extends Fragment) and I have NullPointerException. I have no idea what am I doing wrong. First time I used Activity and in Activity project worked perfect but I use Fragment and I have error
This is a my source
public class Layout1 extends Fragment implements OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener,
SurfaceHolder.Callback, MediaPlayerControl {
MediaPlayer mMediaPlayer;
SurfaceView mSurfaceView;
SurfaceHolder holder;
String video = "http://www.pocketjourney.com/downloads/pj/video/famous.3gp";
MediaController mcontroller;
Handler handler;
String videoUrl;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout1, null);
SurfaceView v = (SurfaceView) view
.findViewById(R.id.screen_tutorial_video_surface);
handler = new Handler();
holder = v.getHolder();
holder.addCallback(this);
playVideo();
return view;
}
private void playVideo() {
try {
mcontroller = new MediaController(getActivity());
mcontroller.setVisibility(View.INVISIBLE);
mMediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(video));
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
mMediaPlayer.setDisplay(holder);
try {
// progressDialog.dismiss();
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void onPrepared(MediaPlayer mp) {
// mcontroller.setMediaPlayer(this);
// mcontroller
// .setAnchorView(findViewById(R.id.screen_tutorial_video_surface));
// mcontroller.setEnabled(true);
//
// handler.post(new Runnable() {
// public void run() {
// mcontroller.show();
// }
// });
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
public void start() {
mMediaPlayer.start();
}
public void pause() {
mMediaPlayer.pause();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mMediaPlayer.seekTo(1);
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
}
Error log
It seems that onSurfaceCreated is called before playVideo(). Initialize your mMediaPlayer (and handler too by the way) in Fragment's onCreate().
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
handler = new Handler();
playVideo();
}
private void playVideo() {
mcontroller = new MediaController(getActivity());
mcontroller.setVisibility(View.INVISIBLE);
mMediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(video));
// implement a fallback mechanism if it fails, for example if no internet or 404
if (mMediaPlayer == null) {
Log.w("Layout1", "Faileded to create MediaPlayer");
return;
}
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout1, null);
SurfaceView v = (SurfaceView) view
.findViewById(R.id.screen_tutorial_video_surface);
v.getHolder().addCallback(this);
return view;
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
if (mMediaPlayer == null) {
// implement a fallback mechanism if it fails, for example if no internet or 404
Log.w("Layout1", "MediaPlayer was not created");
return;
}
// the holder reference is already passed as arg0 here
mMediaPlayer.setDisplay(arg0);
try {
// progressDialog.dismiss();
mMediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
}
}
After you removed catch (Exception e) in playVideo()
If you looked closely in logs you could have seen
Permission failure: android.permission.INTERNET from uid=10052 pid=1129
Request requires android.permission.INTERNET
Unable to create media player
create failed:
java.io.IOException: setDataSource failed.: status=0x80000000
Thus you also need to add permission
<uses-permission android:name="android.permission.INTERNET"/>
If it wasn't for the project you've attached we would never knew.

setLooping don't work in my videoplayer

I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}

Android media player streaming

i am working on android media player, which streams the video and displays. The application is able to buffer but the video is not being displayed on surface view though i am able to hear the sound.
The following is my code:
public class VideoPlayerActivity extends Activity implements OnPreparedListener, OnCompletionListener, OnBufferingUpdateListener, OnSeekCompleteListener, OnErrorListener, SurfaceHolder.Callback {
private VideoView videoView;
private MediaPlayer mp;
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
// surfaceHolder.setFixedSize(176, 144);
// surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
try {
String path = "http://xxxxxxxxxxx/4_xxx.mp4";
mp = new MediaPlayer();
mp.setDataSource(path);
mp.setDisplay(surfaceHolder);
mp.prepare();
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnCompletionListener(this);
mp.setOnSeekCompleteListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
// Uri uri = Uri.parse(path);
//
// videoView = (VideoView) findViewById(R.id.videoView1);
//
// videoView.setVideoURI(uri);
//
// videoView.setMediaController(new MediaController(this));
//
//
//
// videoView.setOnPreparedListener(this);
//
//
//
// videoView.requestFocus();
//
// videoView.start();
}
#Override
public void onPrepared(MediaPlayer mp) {
System.out.println("=======In on prepared======Media Player=====" + mp);
}
#Override
public void onCompletion(MediaPlayer mp) {
System.out.println("=======In on completion====== Media player====" + mp);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
System.out.println("=======In on Buffering update======Media Player====" + mp + "====percent====" + percent);
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
System.out.println("=======In on Error======Media Player====" + mp + "=====what====" + what + "====extra====" + extra);
return false;
}
#Override
public void onSeekComplete(MediaPlayer mp) {
System.out.println("=======In on seek complete======Media Player====" + mp);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mp.setDisplay(holder);
play();
}

Categories

Resources