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) {
}
});
}
Related
when i am play audio player and between playing i am play second audio first audio progress bar and timer sink with second audio player and so on . please help on this .**All audio are loaded in recyclerview.**I want audio Player like whatsapp play audio one by one and there progress bar no sink with each other
if (message.getFileType() == MessageFileType.AUDIO)
{
mediaUrl=message.getFile();
Log.d("tag","mediaURL"+mediaUrl);
Uri video = Uri.parse(mediaUrl);
holder.BtnPlayMusic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
if(flag){
mPlayer = MediaPlayer.create(mContext, video);
flag = false;
}
if ( mPlayer.isPlaying())
{
holder.MusicSeekBar.setProgress(0);
mPlayer.stop();
flag=true;
// mPlayer.reset();
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
mPlayer = MediaPlayer.create(mContext, video);
flag = false;
mPlayer.start();
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
getDurationTimer(holder);
holder.MusicSeekBar.setMax(mPlayer.getDuration()/1000);
getSeekBarStatus(holder);
}
else
{
mPlayer.start();
getDurationTimer(holder);
holder.BtnPlayMusic.setImageResource(R.drawable.pause_button_red);
holder.MusicSeekBar.setMax(mPlayer.getDuration()/1000);
getSeekBarStatus(holder);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
flag=true;
holder.MusicSeekBar.setProgress(0);
}}); }}
});
holder.BtnStopMusic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPlayer.stop();
mPlayer.reset();
flag=true;
// mPlayer.reset();
holder.BtnPlayMusic.setImageResource(R.drawable.play_button_red);
}
});
}
//Creating duration time method
public void getDurationTimer(MessageViewHolder holder){
final long minutes=(mPlayer.getDuration()/1000)/60;
final int seconds= (int) ((mPlayer.getDuration()/1000)%60);
holder.MusicTime.setText(minutes+ "0:0"+seconds);
}
//creating a method for seekBar progress
public void getSeekBarStatus(MessageViewHolder holder){
thread=new Thread(new Runnable() {
#Override
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
holder.MusicSeekBar.setMax(total);
while (mPlayer != null && currentPosition < total && flag==false) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
}
holder.MusicSeekBar.setProgress(currentPosition);
}
}
});
thread.start();
holder.MusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progress=0;
#Override
public void onProgressChanged(final SeekBar seekBar, int ProgressValue, boolean fromUser) {
if (fromUser) {
mPlayer.seekTo(ProgressValue);//if user drags the seekbar, it gets the position and updates in textView.
progress=ProgressValue;
}
final long mMinutes=(ProgressValue/1000)/60;//converting into minutes
final int mSeconds=((ProgressValue/1000)%60);//converting into seconds
holder.MusicTime.setText(mMinutes+"0:0"+mSeconds);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mPlayer.seekTo(progress);
}
});
}
I am using video view to play files I need to raise a toast when the seekbar is clicked or used to seek video showing the current video duration. Any help?
MediaController mediaController = new MediaController(this.context);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
try {
videoView.setVideoURI(Uri.parse(url));
}
catch (Exception e){
Log.i("Error","In making connection");
}
videoView.requestFocus();
try{
videoView.setOnPreparedListener(new android.media.MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(android.media.MediaPlayer mediaPlayer) {
textViewPlayback.setVisibility(View.INVISIBLE);
Log.i("Inside","On prepare");
progressBar.setVisibility(View.INVISIBLE);
videoView.start();
videoView.seekTo(getSeekTime()*1000);
textViewPlayback.postDelayed(onEverySecond,10);
}
});
}
catch (Exception e){
Toast.makeText(this.context,"can not play this file",Toast.LENGTH_SHORT).show();
}
videoView.setOnErrorListener(new android.media.MediaPlayer.OnErrorListener() {
#Override
public boolean onError(android.media.MediaPlayer mediaPlayer, int i, int i1) {
Log.i("Error in playing","error");
return false;
}
});
videoView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
Toast.makeText(getContext(),textViewPlayback.getText(),Toast.LENGTH_SHORT).show();
return false;
}
});
}
I am using video-view player to play and control media. I need to know is there any way that I can find out when the seekbar is touched in the video view controls.
You can use like this -
Add seekbar below your video view.
seekBar = (SeekBar) findViewById(R.id.seek_bar);
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
seekBar.setProgress(0);
seekBar.setMax(recVideo.getDuration());
}
});
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Show toast here
}
#Override
public void onStopTrackingTouch(SeekBar 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 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..
for repeat audio in mediaplayer write this code but not work correct :
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (b) {
G.mediaPlayer.seekTo(i);
}
if (i >= G.mediaPlayer.getDuration()) {
if (isRepeat) {
G.mediaPlayer.seekTo(0);
G.mediaPlayer.start();
}else {
G.mediaPlayer.seekTo(0);
G.mediaPlayer.pause();
}
}
}
and for play audio do this :
public void playSongWithIndex(final int songIndex) {
progressBar.setVisibility(View.VISIBLE);
if (music_exist.exists()) {
playMusicOfflineMode();
} else {
try {
G.mediaPlayer.reset();
G.mediaPlayer.setDataSource(songList.get(songIndex).getFile_128());
G.mediaPlayer.prepareAsync();
G.mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
G.mediaPlayer.start();
seekBar.setMax(G.mediaPlayer.getDuration());
progressBar.setVisibility(View.INVISIBLE);
timer = new Timer();
timer.schedule(new MainTimer(), 0, 1000);
}
});
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
e.printStackTrace();
}
}
}
but repeat audio some times work done and sometimes when seekbar well be over stop and do not work .
please help me how to repeat audio ?
You can set Media player looping to true,use this code:
G.mediaPlayer.setLooping(true);
And if you want to know when the player has finished you should use OnCompletionListener like this:
G.mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
});
ok for help other developer write my correct answer :
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (isRepeat) {
G.mediaPlayer.start();
} else {
G.mediaPlayer.seekTo(0);
seekBar.setProgress(0);
current_duration_text.setText("" + utils.milliSecondsToTimer(0));
play_music_img.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
}
I hope to be useful
i am not sure but i think you can use loop ...for example
mMediaPlayer.setLooping(true);