I am facing the issue in showing the media player .
1) Showing the media controller for only 3 seconds after that media controller is hidden.
2) Media controller should destroy only when the activity is closed or back button pressed.
3) Media controller is viewing the bottom of the activity i want to change the place for media controller viewing.
public void audioplayer(View view)
{
mediaController = new MediaController(this);
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
mediaPlayer.reset();
try {
mediaPlayer.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer((MediaController.MediaPlayerControl) this);
mediaController.setAnchorView(findViewById(R.id.main_audio_view));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
//the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
//--MediaPlayerControl methods----------------------------------------------------
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
//--------------------------------------------------------------------------------
The above code for media controller .In that the media controller is shown for only three seconds.please help me how to solve this.The media player should shown till the song ends and also media controller should hide only when the activity destroyed.
change return statement in public boolean onTouchEvent(MotionEvent event) to true. and Remove if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
i am also new to android hope it Helps..
Related
I am trying to play the song from local storage using MediaPlayer. playing song is working properly, but when i am trying to change mediaPlayer.seekTo(p) with seekBar onProgressChanged listener it always restart the song instead of starting from seeked position. This is not duplicate question i have searched for the solution but nothing works for me.
Code To Play Song:
public void playSong(String path) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(getContext(), Uri.parse(path));
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared: ");
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
Change SeekBar Position Listener:
public void circularSeekBarChangeListener(CircularSeekBar circularSeekBar) {
circularSeekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float progress, boolean fromUser) {
Log.d(TAG, "onProgressChanged: P2 " + progress);
if (fromUser) {
int p = (int) progress;
Log.d(TAG, "onProgressChanged: "+mediaPlayer.getCurrentPosition());
mediaPlayer.seekTo(p);
Log.d(TAG, "onProgress1111 "+mediaPlayer.getCurrentPosition());
}
}
#Override
public void onStopTrackingTouch(CircularSeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar seekBar) {
}
});
}
i am designing a mediaplayer from scratch so what i am getting stuck in is that when the song finish to play i want to set seekbar to initial value
i know this can be done with
seekBar.setProgress(0)
but this don't work with me and i want the play button to switch back to pause button and if the user play song again than the song will be played normally
here is my code of media player and hope you tell me what is the logic and how to place it
public class MusicPlayerActivity extends AppCompatActivity implements Runnable,
SeekBar.OnSeekBarChangeListener {
ImageView playpause;
SeekBar seekBar;
MediaPlayer mp = null;
int len = 0;
boolean isPlaying = false;
public MusicPlayerActivity() throws IOException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
String url = getIntent().getExtras().getString("musicurl");
playpause = (ImageView)findViewById(R.id.imageView);
seekBar = (SeekBar)findViewById(R.id.seekBar);
playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isPlaying){
playpause.setImageResource(R.drawable.pause);
mp.pause();
len = mp.getCurrentPosition();
seekBar.setEnabled(false);
}else{
playpause.setImageResource(R.drawable.play);
mp.seekTo(len);
mp.start();
seekBar.setEnabled(true);
}
isPlaying = !isPlaying;
}
});
mp = new MediaPlayer();
try {
mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//if(mp.isPlaying()) mp.stop(); mp.release();
mp.start();
seekBar.setMax(mp.getDuration());
new Thread(this).start();
// Toast.makeText(this, mp.getDuration(), Toast.LENGTH_SHORT).show();
}
//if(mp.isPlaying()){}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mp.stop();
startActivity(new Intent(this,MainActivity.class));
break;
}
return true;
}
#Override
public void onBackPressed() {
Intent mainActivity = new Intent(Intent.ACTION_MAIN);
mainActivity.addCategory(Intent.CATEGORY_HOME);
mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
}
You are not setting the listener : seekbar.setOnSeekBarChangeListener(this)
Add seekbar.setOnSeekBarChangeListener(this); in your onCreate otherwise the onProgressChanged() does not get called.
To reset progress bar look into the following approach:
Set OnCompletionListener on your media player instance. When the media file completes playing, your can carry out the required actions in OnCompletion(MediaPlayer mp) callback function.
Adding following code snippet before mp.start() should work for you.
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
seekBar.setProgress(0); // sets seekbar to initial position.
toggleViews();//implement this function to toggle your play/pause button
}
});
I have bit of trouble playing back video in my app. I have the very similar code as below playing back my audio files, however, when I try to play video I'm not seeing a picture, I can still hear the narration but no video. Just to exclude encoding, I dropped in my assets a file from my cell that was created on my cell and I was trying to play it back using the above method without luck. Any thoughts would be appreciated, Thank you.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_audio_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<VideoView
android:layout_weight="0.3"
android:id="#+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/fragmentVidListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
public class MediaPlayer extends AppCompatActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "VideoPlayer";
private android.media.MediaPlayer mediaPlayer;
private MediaController mediaController;
private String videoFileName= "test2.mp4";
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_video_view);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
AssetFileDescriptor descriptor = MediaPlayer.this.getAssets().openFd(videoFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + videoFileName + " for playback.", e);
}
}
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.videoView1));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
}
#Override
public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public void onStart() {
super.onStart();
}
}
I am trying to use the mediacontroller to play audio. I am able to get the audio working but when the song starts playing the play button on my mediacontroller does not update. If press the play button on the mediacontroller it pauses the song and seeks the progressbar. Then if i press pause it plays the song again. i am calling
mp.start()
does this not update the play button. How can I get the button to change to the pause button when I call start?
public class QuickMusicPlayer implements MediaController.MediaPlayerControl {
private final MediaPlayer mMediaPlayer;
private final MediaController mMediaController;
private Activity mActivity;
public QuickMusicPlayer(View anchorView, Activity activity) {
mActivity = activity;
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(activity);
mMediaController.setMediaPlayer(this);
mMediaController.setAnchorView(anchorView);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
public void setUrl(String url) {
mMediaPlayer.reset();
if (TextUtils.isEmpty(url)) {
ViewUtil.showCroutonAlert(mActivity, R.string.cant_play_music);
} else {
try {
mMediaPlayer.setDataSource(url);
mMediaPlayer.prepareAsync();
mMediaController.setEnabled(true);
mMediaController.show(0);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public void pause() {
mMediaPlayer.pause();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
Figured it out. I need to call show again after start to update the buttons
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mMediaController.show(0);
}
});
I'm using a media controller associated with a media player to play a sound. The issue is that the media controller is hiding as soon as it loses focus. I have a button which when pressed, the sound is played and the media controller shows up at the bottom of the screen.
But when life pause is pressed, after like 5 seconds, the media controller itself hides.
here are part of my codes. I'm stopping the media player as soon as the media controller hides so that the sound is not continually played
All the codes for the media controller are:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(currentFragment);
mediaController = new MediaController(getActivity()){
#Override
public void hide()
{
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
super.hide();
}
};
try {
mediaPlayer.setDataSource(sound.getSound());
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
mediaPlayer.start();
#Override
public void onPrepared(MediaPlayer mp) {
Log.d("media status", "onPrepared");
handler.post(new Runnable() {
public void run() {
launchMediaController();
progress.dismiss();
}
});
}
void launchMediaController(){
mediaController.setEnabled(true);
mediaPlayer.start();
mediaController.setMediaPlayer(soundController);
mediaController.setAnchorView(getView());
mediaController.show(0);
}
private class SoundController implements MediaController.MediaPlayerControl{
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
Edits:
Based on the answer of Libin, I did the following with no success:
Extends MediaController and overrides touch event
private class MyMediaController extends MediaController{
public MyMediaController(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}
Use extended class
mediaController = new MyMediaController(getActivity()){
#Override
public void hide()
{
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
super.hide();
}
};
launchMediaController() is actually what launches the media controller.
My question, why does the media controller hides by itself after some seconds after the user touches it? Is there any solution to this?
when you call show() , you can set a duration to show the controller on screen. so the controller will automatically hide after 'timeout' milliseconds of inactivity.
You can set the timeout as 0 , to show the controller until the hide is explicitly called.
controller.show(0);
Use 0 to show the controller until hide() is called.
If you use show() method without argument , the default timeout is 3 seconds
Here is some code from show(int timeOut) method call
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
The handler is send a delayed message if the timeout id not 0, and in handler if the message is FADE_OUT the hide method is called
EDIT
There is bug in MediaController code. In the onTouchEvent the default timeout is set , which will override the timeout 0.
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
You can fix this by creating a custom MediaController and override the onTouchEvent
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}