Seekbar does not update - android

I want to play a music so I used seekber to show the progress, everything is fine until I press pause button, the seekbar stops but when I press the play button the seekbar does not move, I figured out it is because of getcurrentposition() method, it does not update after pausing, below is my code, what's wrong with it?
#Override
public void onClick(View v) {
try {
if (isPlaying) {
buttonPlayPause.setImageResource(R.drawable.play);
mediaPlayer.pause();
isPlaying = false;
} else {
buttonPlayPause.setImageResource(R.drawable.pause);
isPlaying = true;
mediaPlayer.start();
primarySeekBarProgressUpdater();
}
} catch (Exception e) {
onDestroy();
}
}
});
private void primarySeekBarProgressUpdater() {
try {
seekBarProgress
.setProgress((int) (((float) mediaPlayer
.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
} catch (Exception e) {
onDestroy();
}
}

Related

How to play and pause audio in firebase recyclerview in android

I am developing an app in which I have to fetch audio from firebase. I am using firebase recycler view. I am getting a problem that when I click the first song it plays good, but when I click second item then the first song's play button does not change and seekbar of first and second song changes.
Here is the code.
holder.play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String audioUrl3 = model.getMedia();
if (!isPlaying){
if (mPlayer!=null){
mPlayer.release();
}
Toast.makeText(mContext, "Loading....", Toast.LENGTH_SHORT).show();
isPlaying = true;
Uri uri = Uri.parse(audioUrl3);
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.reset();
try {
mPlayer.setDataSource(mContext,uri);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
}
try{
mPlayer.prepareAsync();
}catch (Exception e){
Toast.makeText(mContext, "Error Occured", Toast.LENGTH_SHORT).show();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(mPlayer.isPlaying()){
mPlayer.stop();
}
mPlayer.start();
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_pause));
holder.seekBar.setMax(mPlayer.getDuration());
Toast.makeText(mContext, "Playing...", Toast.LENGTH_SHORT).show();
updateSeekBar(holder.seekBar);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
isPlaying = false;
}
});
}
else {
isPlaying=false;
stopPlaying();
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer=null;
holder.play_btn.setImageDrawable(holder.play_btn.getContext().getResources().getDrawable(R.drawable.ic_play));
}
});
}
private void updateSeekBar(final SeekBar seek) {
try{
int pos = mPlayer.getCurrentPosition();
seek.setProgress(pos);
}catch (Exception e){
}
runnable = new Runnable() {
#Override
public void run() {
updateSeekBar(seek);
}
};
handler.postDelayed(runnable, 1800);
}

Adding delay while Mediaplayer loops

Playing .wav file using MediaPlayer class. As I need to loop the Audio I've set .setLooping(true); . So obviously, the doubt is how do I add a delay each time the audio plays, say I want a delay of 5000 .
The answers to similar questions here doesn't work in my case. Any help would be appreciated. Here is my code:
Button Sample = (Button)findViewById(R.id.samplex);
Sample.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filePath = Environment.getExternalStorageDirectory()+"/myAppCache/wakeUp.wav";
try {
mp.setDataSource(filePath);
mp.prepare();
mp.setLooping(true);
}
catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
You need to register 2 listeners (on completion and on error) and then you would need to delay next play in on completion callback. Reason for the error listener is to return true to avoid calling on completion event whenever there is an error - explanation here
private final Runnable loopingRunnable = new Runnable() {
#Override
public void run() {
if (mp != null) {
if (mp.isPlaying() {
mp.stop();
}
mp.start();
}
}
}
mp.setDataSource(filePath);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
button.postDelayed(loopingRunnable, 5000);
}
});
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
...
return true;
});
mp.prepare();
// no need to loop it since on completion event takes care of this
// mp.setLooping(true);
Whenever your destruction method is (Activity.onDestroyed(), Fragment.onDestroy(), View.onDetachedFromWindow()), ensure you are removing the runnable callbacks, e.g.
#Override
protected void onDestroy() {
super.onDestroy();
...
button.removeCallbacks(loopingRunnable);
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
mp = null;
}
}

how to stop viewpager auto slide in android

I have made an android app in that i have implemented play pause function,But I only knows about play ,I don't know how to stop sliding on the same button click,I have used two functions for it as below,play is working but pause is not.!
onClick
if (!flag) {
play();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.pause);
flag = true;
} else {
pause();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.play_btn);
flag = false;
}
play and pause
void play() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 3000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
void pause() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 300000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
in pause button click :
handler.removeCallbacksAndMessages(ViewPagerVisibleScroll);
Try this

How to get duration of video when it is recording-Android

I'm facing with a problem. I want to get duration of video when i 'm recording it.
I can get duration of video when it's finish by code
MediaPlayer mp = MediaPlayer.create(mContext, Uri.parse(video));
if(mp == null)
return -1;
int duration = mp.getDuration();
mp.release();
But i want to get duration everytime when i record video to update to progressbar.
Hope your reply!
private class PlaybackObserver extends Thread {
public void run() {
currentPosition = 0;
try {
while (!killObserverThread) {
Thread.sleep(1000);
currentPosition = (int) mediaPlayer.getCurrentPosition();
runOnUiThread(new Runnable() {
public void run() {
yourProgressBar.setProgress(currentPosition);
}
});
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
killObserverThread = false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if (task == null || !task.isAlive()) {
task = new PlaybackObserver();
task.start();
}
startPlaying();
}
add a private class for your UiThread to update your seekbar/progressbar. Then start it from onResume()

Method inside Thread is going out of focus

I have a method which I am calling from onCreate( main thread). Inside the method I am calling one more method and a Runnable that calls the same method repeatedly. This is how it looks,
public void start() {
try {
if (start == 0) {
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.play));
initialPoiPlayStatus = true;
playAudio();
}
if (play) {
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
// for displaying view stub
poi = listOfPOI.get(j);
int pos = mMediaPlayer.getCurrentPosition();
int convSeconds = -1;
convSeconds = ((int) (pos) / 1000);
// displaying the you tube pop up based on the parsed value
// from the plist
youTube(convSeconds);
// call the method to change the image while the audio is
// playing
changeImage();
seek_bar.setProgress(current_position);
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
} else {
if (j != (listOfPOI.size() - 1)) {
firstPlay = true;
initialPoiPlayStatus = true;
j++;
playAudio();
start();
// retrieve mascot info
if (isNetworkAvailable() == true) {
receiveResponse();
} else {
}
} else {
threadHandler.sendEmptyMessage(0);
}
}
}
} catch (Exception e) {
System.out.println(poi.getPlistPath());
e.printStackTrace();
}
}
Now inside youtube,
private void youTube(int convSeconds) {
frameLayout = (FrameLayout) findViewById(R.id.frameLayout);
youtubeWebView = (WebView) findViewById(R.id.youtubewebView);
try {
if (poi.getIsYoutubePresent().equals("true")) {
//mMediaPlayer.pause();
isNetworkAvailable();
if (isNetworkAvailable() == true) {
String startTimeyoutube = poi.getYoutubestartTime();
Integer youTubeStartTime = Integer
.parseInt(startTimeyoutube);
if (convSeconds == youTubeStartTime) {
if (frameLayout.getVisibility() == View.GONE) {
frameLayout.setVisibility(View.VISIBLE);
slideUp = AnimationUtils.loadAnimation(this,
R.anim.slide_up);
frameLayout.startAnimation(slideUp);
}
final String youTubeurl = poi.getLink();
WebSettings websets = youtubeWebView.getSettings();
websets.setJavaScriptEnabled(true);
registerForContextMenu(youtubeWebView);
youtubeWebView
.setWebViewClient(new ItemsWebViewClient());
youtubeWebView.loadUrl(youTubeurl);
youtubeWebView.getSettings().setLayoutAlgorithm(
LayoutAlgorithm.SINGLE_COLUMN);
firstPlay = false;
initialPoiPlayStatus = false;
paused = true;
play = false;
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.play));
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
Button goBtn = (Button) findViewById(R.id.youtubeButton);
goBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse(youTubeurl)));
}
});
ImageButton close = (ImageButton) findViewById(R.id.youtubecloseButton);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frameLayout.setVisibility(View.GONE);
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
playpause.setBackgroundDrawable(getResources().getDrawable(
R.drawable.pause));
}
});
}
} else {
Toast.makeText(getApplicationContext(), "No network available", Toast.LENGTH_SHORT).show();
}
} else {
frameLayout.setVisibility(View.INVISIBLE);
}
} catch (Exception e) {
e.printStackTrace();
}
return;
}
Here whenever, if (convSeconds == youTubeStartTime) {} becomes true, I am making my audio pause i.e.,
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
And during this time also I want the start() inside Runnable notification should be keep calling. But if I make audio pause this is not happening only. The control is completely lost in this case. And on pressing the Image button close, i am trying to make the audio again to play like this
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
Audio keeps playing now, but the slider/seekbar is not moving because start() inside notification is not getting called.
Do any one know why is it happening like this?
Note: How ever if I don make my mediaplayer not to pause, it works fine. I get the problem onky when I make the audio to pause
I solved the issue finally, it may not be the standard way. But it is working for me.
i just replicated
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
where I am trying to close the image button, i.e.,
ImageButton close = (ImageButton) findViewById(R.id.youtubecloseButton);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
frameLayout.setVisibility(View.GONE);
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
notification = new Runnable() {
public void run() {
start();
}
};
handler.postDelayed(notification, 1000);
}
});

Categories

Resources