How to prebuffer VideoView A while another VideoView B is playing - Android - android

I am interested in being able to "prebuffer" VideoView A while VideoView B is playing. Is this possible?
I have two instances of a VideoView.
Only one VideoView will be displayed at a given time, taking up the entire screen of the phone.
The purpose is to reduce the "black screen" when switching from VideoView A and VideoView B.
The app plays a list of videos one after another.
Added Below Code on Jan 19, 2015
The code below grabs a reference to each Player's MediaPlayer. When MediaPlayer A begins rendering, MediaPlayer B will call stop(), release(), setDataSource(url), prepareAsync(). When MediaPlayer A completes, Media Player B will call start().
public class PrebufferingActivity extends Activity {
private VideoView player1;
private VideoView player2;
private MediaPlayer mediaPlayer1;
private MediaPlayer mediaPlayer2;
public static final String URL_1 = "sample1.mp4";
public static final String URL_2 = "sample2.mp4";
public boolean FIRST_TIME = true;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prebuffering);
player1 = (VideoView) findViewById(R.id.videoPlayer1);
player2 = (VideoView) findViewById(R.id.videoPlayer2);
player1.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
player2.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
player1.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer2.start();
// Toggle visibility. Player1 is completed. Hide Player1. Show Player2.
player2.setVisibility(View.VISIBLE);
player1.setVisibility(View.INVISIBLE);
}
});
player1.setOnInfoListener(new OnInfoListener(){
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
if(what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
{
mediaPlayer2.stop();
mediaPlayer2.release();
try {
mediaPlayer2.setDataSource(URL_2);
mediaPlayer2.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
});
player1.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer1 = mp;
if(FIRST_TIME == true) {
mediaPlayer1.start();
player1.requestFocus();
FIRST_TIME = false;
}
}
});
player2.setOnCompletionListener(new OnCompletionListener(){
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer1.start();
player1.requestFocus();
// Toggle visibility. Player2 is completed. Hide Player2. Show Player1.
player1.setVisibility(View.VISIBLE);
player2.setVisibility(View.INVISIBLE);
}
});
player2.setOnInfoListener(new OnInfoListener(){
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
if(what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START)
{
// Prepare Player 2
mediaPlayer1.stop();
mediaPlayer1.release();
try {
mediaPlayer1.setDataSource(PrebufferingActivity.URL_1);
mediaPlayer1.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
});
player2.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer2 = mp;
}
});
// Player 1
player1.setMediaController(new MediaController(this));
player1.setVideoURI(Uri.parse(URL_1));
// Player 2
player2.setMediaController(new MediaController(this));
player2.setVideoURI(Uri.parse(URL_2));
}

Assuming you are using MediaPlayer to handle the playback of your videos within your VideoView, you can use the prepareAsync() method to achive this. The prepareAsync() method essentially performs the same function as prepare(), which is used to buffer and prepare a video, except it can be done asynchronously in the background.
EDIT
I did something similiar but I actually used SurfaceView. To handle another stream, simply create another instance of MediaPlayer. The following example will create two instances of MediaPlayer and buffer the first video. After the first video is prepared, the second video will be asynchronously buffered. The first MediaPlayer is then bound to the SurfaceView and the first video is started. When the first video is finished playing, the corresponding instance of MediaPlayer is released, the secondary instance is attached, and the second video is automatically started. The following example code has been tested and works fine:
public class StreamingActivity extends Activity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
MediaPlayer mediaPlayerPrimary;
MediaPlayer mediaPlayerSecondary;
SurfaceHolder surfaceHolder;
SurfaceView surfaceView;
String videoSourcePrimary = "videoSourcePrimaryURL";
String videoSourceSecondary = "videoSourceSecondaryURL";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.streaming_activity_layout);
/** Create SurfaceView */
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder arg0)
{
try
{
/** Create MediaPlayer(s) */
mediaPlayerPrimary = new MediaPlayer();
mediaPlayerSecondary = new MediaPlayer();
/** Attach primary MediaPlayer to SurfaceView */
mediaPlayerPrimary.setDisplay(surfaceHolder);
/** Set sources */
mediaPlayerPrimary.setDataSource(videoSourcePrimary);
mediaPlayerSecondary.setDataSource(videoSourceSecondary);
/** Prepare MediaPlayer(s) */
mediaPlayerPrimary.prepare();
mediaPlayerSecondary.prepareAsync();
/** Set listeners */
mediaPlayerPrimary.setOnPreparedListener(this);
mediaPlayerPrimary.setOnCompletionListener(this);
mediaPlayerSecondary.setOnPreparedListener(this);
mediaPlayerSecondary.setOnCompletionListener(this);
/** Set audio stream type */
mediaPlayerPrimary.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayerSecondary.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3)
{
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0)
{
}
#Override
public void onPrepared(MediaPlayer mp)
{
if (mp == mediaPlayerPrimary)
{
/** First video ready, start playback */
mediaPlayerPrimary.start();
}
else if (mp == mediaPlayerSecondary)
{
/** Second video is ready */
}
}
#Override
public void onCompletion(MediaPlayer mp)
{
/** First video is completed, start second video */
mediaPlayerPrimary.release();
mediaPlayerSecondary.setDisplay(surfaceHolder);
mediaPlayerSecondary.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.streaming_activity_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

MediaPlayer doesn't resume video after activity restart

I have a MediaPlayer object that uses a SurfaceHolder object as a surface. There is a button on top of the video that takes me out of the video to a website. When that happens, I pause the player with player.pause(). When I return from the website, I resume the player with player.start(). I know that the surface gets destroyed when the activity is not displayed anymore, and it gets recreated as soon as the activity is restarted. In my surfaceCreated(), I set the surface for the player again (since it no longer has a surface at that point), and then resume. However, the player simply restarts the video from the beginning.
I've tried commenting out the line that takes me to the website, just to see if pause/start works properly and resumes from last spot. It does. I'm not sure why this behaviour doesn't happen when I leave and re-enter the video activity though.
I also tried using the player.seekTo() call. There was no difference. In fact, when I disabled the button taking me to a site to just pausing the video, with the seekTo() call the video ALSO started from the beginning despite position being not 0.
The player object is the same all the way throughout.
Just because the surface is a new one on restart, it doesn't know or care of its contents, does it? The player should be managing that, right?
I'm out of ideas at this point. Can anyone please offer any tips?
UPDATE: So I threw together a quick app just to eliminate any other external factors. Here's the full code for the video class (other class is just an activity with a play button):
public class VideoPlayer extends Activity implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnVideoSizeChangedListener,
SurfaceHolder.Callback {
private MediaPlayer player;
private SurfaceHolder mSurfaceHolder;
private SurfaceView mSurfaceView;
private Button leaveVideoButton;
private boolean isPaused = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_layout);
leaveVideoButton = (Button) findViewById(R.id.go_to_web);
leaveVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri uri = Uri.parse("http://www.google.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
pauseSteps();
startActivity(intent);
}
});
createPlayer();
createSurface();
}
private void createSurface() {
mSurfaceView = (SurfaceView) findViewById(R.id.surface);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private void createPlayer() {
player = new MediaPlayer();
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.setOnVideoSizeChangedListener(this);
player.setOnSeekCompleteListener(this);
}
private void pauseSteps() {
if(player.isPlaying()) {
player.pause();
isPaused = true;
}
}
private void playSteps() {
if(isPaused) {
isPaused = false;
player.start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (player.isPlaying()) {
player.stop();
}
player.reset();
player.release();
player = null;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
if (!isPaused) {
try {
// player.setDataSource(path);
AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.video);
if (afd == null) return;
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
} else {
playSteps();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
player.start();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
}
}
UPDATE 2: So I tried a different video and it resumed just fine from the same spot. This must be some encoding issue.

Android native media player not firing onCompletion method

Native Android Media player does not invoke onCompletion method after the video has ran it's duration.
I have an Activity that plays a single video or a list of videos (m3u8 file). Video plays file as it should, I can use the media controller as well, however, when the video runs out, after a few seconds he starts a loop. onCompletion method doesn't activate unless the user clicks (or double taps) the fast forward option on media controler.
Is there a way to make the onComplete method activate automatically when the video runs out? (I've tried using the listener, doesn't work). Pointing out what I did wrong also works.
Here is the activity that handles video playing:
public class VideoActivity extends ActionBarActivity implements MediaPlayer.OnCompletionListener {
private static final String TAG = VideoActivity.class.getSimpleName();
private VideoView mVideoViewStream1;
ProgressDialog mDialog;
private String mURL;
private ChannelPlaylist mChannelPlaylist;
private int mIndex;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
// Validate internet connection
if (!Util.isDeviceConnected(this)) {
FragmentManager fm = getSupportFragmentManager();
PopUpErrorFragment popupError = PopUpErrorFragment.newInstance(getString(R.string.errorInternetConnection));
popupError.show(fm, PopUpErrorFragment.TAG);
finish();
}
// Assign controls to their variable representations
mVideoViewStream1 = (VideoView) findViewById(R.id.vvVideo);
// Retrieve bundle data
Intent i = getIntent();
Bundle bundle = i.getExtras();
ChannelPlaylist channelPlaylist = bundle.getParcelable(KeyHelper.BUNDLE_CHANNEL_PLAYLIST);
if (channelPlaylist != null) {
this.mChannelPlaylist = channelPlaylist;
if (bundle.containsKey("index") && mIndex == 0) {
this.mIndex = bundle.getInt("index");
} else {
if (this.mIndex == 0) {
this.mIndex = this.mChannelPlaylist.getIndex();
}
}
this.mURL = this.mChannelPlaylist.getSchedule().get(mIndex).getStream_url();
} else {
this.mURL = bundle.getString("url");
}
progressDialog();
standardAndroidPlayer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.video, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/***************************** CLASS METHODS **************************************************/
/**
* Dismissess the dialog
*/
private void dismissDialog() {
if (this.mDialog != null) {
mDialog.dismiss();
}
}
/**
* Standard android player
*/
private void standardAndroidPlayer() {
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(mVideoViewStream1);
// Get the URL from String VideoURL
mVideoViewStream1.setMediaController(mediacontroller);
// Set media player completion listener
mVideoViewStream1.setOnCompletionListener(this);
mVideoViewStream1.setVideoURI(Uri.parse(this.mURL));
mVideoViewStream1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
//Log.i(TAG, "Duration = " + mVideoViewStream1.getDuration());
if (mp.isLooping()) mp.setLooping(false);
}
});
mVideoViewStream1.requestFocus();
mVideoViewStream1.start();
} catch (Exception e) {
dismissDialog();
Log.e(TAG, "Error" + e.getMessage());
e.printStackTrace();
}
dismissDialog();
}
#Override
public void onCompletion(MediaPlayer mp) {
this.mIndex++;
if (this.mIndex < mChannelPlaylist.getSchedule().size()) {
this.mURL = this.mChannelPlaylist.getSchedule().get(this.mIndex).getStream_url();
standardAndroidPlayer();
} else {
finish();
}
}
/**
* Creates a progress dialog
*/
private void progressDialog() {
// Create a progressbar
mDialog = new ProgressDialog(VideoActivity.this);
// Set progressbar title
mDialog.setTitle("Android Video Streaming Tutorial");
// Set progressbar message
mDialog.setMessage("Buffering...");
mDialog.setIndeterminate(false);
mDialog.setCancelable(false);
// Show progressbar
mDialog.show();
}
}
Edited:
Ok, for some strange reason, on mobile phone the method doesn't fire off, however when used on tablet, it does. I wasn't able to reproduce the effect on tablet and didn't have any success on the phone either. Does it have something to do with the versions of android? Since I didn't get any warnings about compatibility when writing the listener, I didn't think much about it.
Try this.
mVideoViewStream1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
finish();
}
});

How to start audio streaming from particular position in seekbar android

I am working on audio streaming android application in this I get song url from server which i am playing using audio streaming application in this when I start playing it starts and it shows buffering also but my problem is when i move seekbar to particular position which is not buffered seekbar handle is moving back.actually I need to start playing song from that position.
see my code and please tell me how to handle this scenario
public class StreamingMp3Player extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;
private MediaPlayer mediaPlayer;
private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class
private final Handler handler = new Handler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
}
/** This method initialise all the views in project*/
private void initView() {
buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
buttonPlayPause.setOnClickListener(this);
seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
seekBarProgress.setMax(99); // It means 100% .0-99
seekBarProgress.setOnTouchListener(this);
editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
editTextSongURL.setText("http://instilltech.netii.net/01LECHIPODAMA.mp3");
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
seekBarProgress.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
try {
mediaPlayer.setDataSource(editTextSongURL.getText().toString()); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mediaPlayer.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets the song length in milliseconds from URL
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
buttonPlayPause.setImageResource(R.drawable.button_pause);
}else {
mediaPlayer.pause();
buttonPlayPause.setImageResource(R.drawable.button_play);
}
primarySeekBarProgressUpdater();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId() == R.id.SeekBarTestPlay){
/** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/
if(mediaPlayer.isPlaying()){
SeekBar sb = (SeekBar)v;
int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
mediaPlayer.seekTo(playPositionInMillisecconds);
}
}
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
/** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
buttonPlayPause.setImageResource(R.drawable.button_play);
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
seekBarProgress.setSecondaryProgress(percent);
}
}

Playing audio file in android

I got stuck with one requirement i need to play a media file in android.I will post the screen shot of the page
Actual requirement is the user wants to play the audio file in his recordings list.The recordings list are shown through list adapter.I want to display the play progress of the audio file on the same page(as like shown in the screen shot).
Iam pasting the code which i have tried.
public class RecordingActivity extends ListActivity implements MediaPlayerControl {
MediaPlayer mMediaPlayer;
MediaController mMediaController;
Handler mHandler;
String OUTPUT_FILE;
RelativeLayout rl;
Context context = null;
Point p;
static final String[] recordings = new String[] {"Example1","Example2",
"Example3","Example4","Example5" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new FirstAdapter(this, recordings));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
showPopup(RecordingActivity.this, p);
// get selected items
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mHandler = new Handler();
mMediaController.setMediaPlayer(RecordingActivity.this);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/recorder.mp3";
try{
mMediaPlayer.setDataSource(OUTPUT_FILE);
mMediaPlayer.prepare();
}
catch(Exception e){
}
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(10000);
mMediaPlayer.start();
mMediaController.setEnabled(true);
}
});
}
});
}
private void showPopup(final Activity context, Point p) {
int popupWidth = 200;
int popupHeight = 150;
// Inflate the popup_layout.xml
RelativeLayout viewGroup = (RelativeLayout) context.findViewById(R.id.reviewlist);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_play, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 30;
int OFFSET_Y = 30;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY,p.x+OFFSET_X,p.y+OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
ImageButton close = (ImageButton) layout.findViewById(R.id.close);
Button b1 =(Button) layout.findViewById(R.id.button1);
Button b2 =(Button) layout.findViewById(R.id.button2);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
mMediaController.show();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show();
return false;
}
}
The problem am facing is i am able to play the audio file ,but it is not showing any popup layout.
Media player
MediaPlayer mp = new MediaPlayer();
// Set data source -
setDataSource("/sdcard/path_to_song");
// Play audio
mp.start();
// Pause audio
mp.pause();
// Reset mediaplayer
mp.reset();
// Get song length duration - in milliseconds
mp.getDuration();
// Get current duration - in milliseconds
mp.getCurrentDuration();
// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds
// Check if song is playing or not
mp.isPlaying(); // returns true or false
Hope this will give you some solution. Refer this link. It will solve your problem
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(PlayAudioActivity.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
String audioFile = "" ;
try {
mMediaPlayer.setDataSource(audioFile);
mMediaPlayer.prepare();
} catch (IOException e) {
System.out.println("Error in playing audio");
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(10000);
mMediaPlayer.start();
}
});
}
});
}
if you have done this then.
#Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show();
return false;
}
}
public class PlayAudioActivity extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
use this .

Adding additional methods to MediaController buttons

I have a VideoView which plays a video and I call
videoPlayer.setMediaController(new MediaController(this));
to show the media controller buttons (play, pause, forward, backward).
The question is how am I able to add additional methods when I click the play or pause button of the MediaController?
Here's my class:
public class VideoPlayer extends Activity implements OnCompletionListener {
private String filename;
private VideoView videoPlayer;
private MediaPlayer mediaplayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.video_player);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("video_url");
System.out.println(filename);
videoPlayer = (VideoView) findViewById(R.id.videoPlayer);
videoPlayer.setOnCompletionListener(this);
videoPlayer.setKeepScreenOn(true);
videoPlayer.setVideoPath(filename);
videoPlayer.setMediaController(new MediaController(this));
videoPlayer.requestFocus();
videoPlayer.start();
mediaplayer = new MediaPlayer();
mediaplayer = MediaPlayer.create(
this,
Uri.parse("android.resource://" + getPackageName() + "/"
+ R.raw.alo));
mediaplayer.start();
}
/** This callback will be invoked when the file is finished playing */
#Override
public void onCompletion(MediaPlayer mp) {
// Statements to be executed when the video finishes.
this.finish();
}
/** Use screen touches to toggle the video between playing and paused. */
#Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
if (videoPlayer.isPlaying()) {
videoPlayer.pause();
mediaplayer.pause();
} else {
videoPlayer.start();
mediaplayer.start();
}
return true;
} else {
return false;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I'm not sure what you are trying to achieve.
You could extend a class with MediaController and implement some methods of your own. Basic OO principles.
private class MyMediaController extends MediaController {
#Override
public boolean onTouchEvent(MotionEvent event) {
// Your logic here
return super.onTouchEvent(event);
}
}

Categories

Resources