ProgressBar blocked while MediaPlayer is playing - android

I'm trying to make a circular progress of the MediaPlayer, so it's indeterminate while it's preparing and setting progress while it's playing.
I've tried a lot of ways, but this is my last one: I update the bar on a AsyncTask<Object, Object, Object>.
The class I'm using is CircularProgressView but I've tried to swap to ProgressBar and the behavior is the same:
public void startPlaying(final Audio audio, final CircularProgressView progress_view) {
if (!isPLAYING) {
progress_view.setIndeterminate(true);
progress_view.setVisibility(View.VISIBLE);
progress_view.startAnimation();
isPLAYING = true;
audioPlaying = audio;
mp = new MediaPlayer();
new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... objects) {
try {
mp.prepare();
publishProgress((int)-1);
mediaFileLengthInMilliseconds = mp.getDuration();
mp.start();
while (mp != null && mp.isPlaying()) {
Thread.sleep(100);
publishProgress((int) (mp.getCurrentPosition()));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
mp.setDataSource(audio.getFile().getUrl());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPlaying();
publishProgress((int)-2);
}
});
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setIndeterminate(false);
progress_view.setMaxProgress(mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
System.out.println("setting: " + values[0]);
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}.execute();
} else {
isPLAYING = false;
stopPlaying();
}
}
on debug, the ProgressBar or CircularProgressView .setProgress() is called during the audio reproduction, but it remains blocked in indeterminate, but progress_view.setIndeterminate(false) is called as well, and it doesn't become indeterminate.
When the audio finishes, the ProgressBar or CircularProgressView gets 100% progress.
Any clue?
Thank you very much in advance.
EDIT:
as #Blackbelt suggested, I had to call mediaFileLengthInMilliseconds = mp.getDuration(); before publishProgress((int)-1);
but now this is the behavior:
https://drive.google.com/file/d/0B-V0KHNRjbE_b3hkbkwtTXhIeTg/view?usp=sharing
EDIT 2: Log of mp.getDuration() and mp.getCurrentPosition():
http://pastebin.com/g93V5X9F
or maybe this is more clear:
http://pastebin.com/kYm01Gpg
called on this part:
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setIndeterminate(false);
progress_view.setMaxProgress(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int)values[0]);
}
}
EDIT 3: I'm adding the new code, commenting out the functions setIndeterminate(boolean) and swapping into ProgressBar:
XML:
<ProgressBar
android:id="#+id/progress_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="false"
android:progress="40"
android:visibility="gone"
android:layout_alignTop="#+id/play_button"
android:layout_alignLeft="#+id/play_button"
android:layout_alignStart="#+id/play_button"
android:layout_alignRight="#+id/play_button"
android:layout_alignEnd="#+id/play_button"
android:layout_alignBottom="#+id/play_button" />
Java:
public void startPlaying(final Audio audio, final ProgressBar progress_view) {
if (!isPLAYING) {
Log.i("Stackoverflow", "startPlaying called");
audio.put("times_listened", audio.getTimes_Listened() + 1);
audio.saveEventually();
progress_view.setVisibility(View.VISIBLE);
isPLAYING = true;
audioPlaying = audio;
mp = new MediaPlayer();
new AsyncTask<Object, Object, Object>() {
#Override
protected Object doInBackground(Object... objects) {
try {
mp.prepare();
mediaFileLengthInMilliseconds = mp.getDuration();
publishProgress((int)-1);
mp.start();
while (mp != null && mp.isPlaying()) {
Thread.sleep(100);
publishProgress((int) (mp.getCurrentPosition()));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
mp.setDataSource(audio.getFile().getUrl());
} catch (IOException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
stopPlaying();
publishProgress((int)-2);
}
});
}
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setMax(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int)values[0]);
System.out.println("setting: " + values[0]);
}
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
}
}.execute();
} else {
isPLAYING = false;
stopPlaying();
}
}
EDIT 4:
I'm calling progress_view.isDeterminate() and it's returning me true everytime. So I decided to do when modifying the progress:
#Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
int value = (int)values[0];
if (value == -1) {
progress_view.setMax(mediaFileLengthInMilliseconds);
Log.i("Stackoverflow:", "setMaxProgress to " + mediaFileLengthInMilliseconds);
} else if (value == -2) {
progress_view.setVisibility(View.GONE);
} else {
if (progress_view.isIndeterminate()) // LOOK AT THIS
progress_view.setIndeterminate(false);
progress_view.setProgress((int) values[0]);
Log.i("Stackoverflow:", "setProgress to " + (int) values[0]);
Log.i("Stackoverflow", "Indeterminate state: " + progress_view.isIndeterminate());
System.out.println("setting: " + values[0]);
}
}
and the output is always:
Indeterminate state: true
*WHY ? * :'(

Probably you want to call mediaFileLengthInMilliseconds = mp.getDuration(); before calling publishProgress((int)-1); and not after, or not using that member at all, since you keep already the MediaPlayer as member, you could query directly it.
Edit
To fix the problem in your video, you have to use the following style style="#android:style/Widget.ProgressBar.Horizontal. With the circular ProgressBar, the setIndetermiate flag is ignored

Related

Media player doesn't play recording , when media recording is paused

i am working on a app where user can record audio,pause it if api level is above 23.And user can listen to the paused recording.
But what i found is, user is unable to listen to paused audio. But what i want is user can listen to paused audio
When recording is stopped it is playable as it is stored in a local path.
I also checked android documentation and many answers on stack overflow like how to play paused audio but i can't find any particular links.
i am sharing my question here. if you have any solution or find any link how to solve my problem it is highly appreciated.
Please let me know even if i need to share my code. As i didn't find it necessary to share code. because when user stops the recording, it should be playable.
Below is my code
public class AudioRecordingActivity extends BaseActivity
implements AppDialog.IYesListener,
AppDialog.IDiscardRecordingListener, AppDialog.ICancelRecordingListener,
PlayAudioManager.IVoiceCompleteListener,
MediaRecorder.OnInfoListener {
private static final Logger LOGGER = LoggerFactory.createLogger(AudioRecordingActivity.class);
private TaskDetailsViewModel mViewModel;
private ActivityAudioRecordingBinding mBinding;
private AssignmentIdsModel mAssignmentIdModel;
private long mStartTime = 0;
private long mPauseTime=0;
private MediaRecorder mRecorder;
private File mOutputFile;
public final ObservableField<Integer> mAudioState = new ObservableField<>(0);
private String mAudioPath;
private int mMaxAudioTime;
private int[] amplitudes = new int[100];
private int i = 0;
private Handler mHandler = new Handler();
private PlayAudioManager mAudioManager;
private Runnable mTickExecutor = new Runnable() {
#Override
public void run() {
tick();
mHandler.postDelayed(mTickExecutor, 1000);
}
};
#Override
protected void onCreatingBase(Bundle savedInstanceState, Intent intent) {
mViewModel = ViewModelProviders.of(this).get(TaskDetailsViewModel.class);
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_audio_recording);
mAudioManager = new PlayAudioManager();
mAssignmentIdModel = intent.getParcelableExtra(AppConstants.AppExtras.EXTRA_ASSIGNMENT_MODEL);
mMaxAudioTime = Integer.parseInt(intent.getStringExtra(AppConstants.AppExtras.EXTRA_DURATION));
mAudioPath = MediaUtils.getAudioPath(this, mAssignmentIdModel);
mBinding.ivBack.setOnClickListener(this);
mBinding.rlRecording.setOnClickListener(this);
mBinding.ivPlayAudio.setOnClickListener(this);
mBinding.ivAudioDelete.setOnClickListener(this);
mBinding.tvSave.setOnClickListener(this);
setPlayIconClickable(false);
setSaveButtonClickable(false);
setCrossIconClickable(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.iv_back:
onBackPressed();
break;
case R.id.rl_recording:
startStopRecording();
break;
case R.id.iv_play_audio:
playStopMediaPlayer();
break;
case R.id.iv_audio_delete:
AppDialog.showDeleteAudioDialog(this, this);
break;
case R.id.tv_save:
saveRecording();
break;
}
}
private void saveRecording() {
mViewModel.saveMediaResponse(mAssignmentIdModel, mAudioPath);
finish();
}
private void playStopMediaPlayer() {
if (mAudioManager.isMediaPlayerPlaying()) {
mBinding.ivPlayAudio.setImageResource(R.drawable.play_after_recording_icon);
setSaveButtonClickable(true);
setCrossIconClickable(true);
setPlayIconClickable(true);
mAudioManager.killMediaPlayer();
mBinding.rlRecording.setClickable(true);
mBinding.rippleBackground.stopRippleAnimation();
} else {
playRecording();
}
}
private void startStopRecording() {
switch (mAudioState.get()) {
case AudioRecordingEnum.AUDIO_IDLE_STATE:
hasAudioPermission();
break;
case AudioRecordingEnum.AUDIO_RECORDING_STATE:
pauseStopRecording();
break;
case AudioRecordingEnum.AUDIO_PAUSE_STATE:
resumeRecording();
break;
case AudioRecordingEnum.AUDIO_STOP_STATE:
AppDialog.showNewRecordingDialog(this, this);
break;
}
}
private void hasAudioPermission() {
if (PermissionUtils.hasPermissions(this, PermissionUtils.RC_REQUEST_PERMISSION_RECORD_AUDIO,
Manifest.permission.RECORD_AUDIO)) {
startRecording();
}
}
private void tick() {
long time = (mStartTime < 0) ? 0 : (SystemClock.elapsedRealtime() - mStartTime);
int minutes = (int) (time / 60000);
int seconds = (int) (time / 1000) % 60;
int milliseconds = (int) (time / 100) % 10;
mBinding.tvTimer.setText((minutes < 10 ? "0" + minutes : "00") + ":" + (seconds < 10 ? "0" + seconds : seconds));
if (mRecorder != null) {
amplitudes[i] = mRecorder.getMaxAmplitude();
LOGGER.debug("Voice Recorder", "amplitude: " + (amplitudes[i] * 100 / 32767));
if (i >= amplitudes.length - 1) {
i = 0;
} else {
++i;
}
}
}
private void deleteRecording() {
AppUtils.deleteFile(mAudioPath);
mAudioState.set(AudioRecordingEnum.AUDIO_IDLE_STATE);
setPlayIconClickable(false);
setCrossIconClickable(false);
setSaveButtonClickable(false);
mStartTime = 0;
mBinding.tvTimer.setText("00:00");
mBinding.tvStartRecording.setText(getResources().getString(R.string.txt_start_recording));
mBinding.rlRecording.setClickable(true);
}
private void playRecording() {
try {
Uri videoUri = FileProvider.getUriForFile(this,
this.getApplicationContext().getPackageName() + ".provider",
mOutputFile);
mAudioManager.playAudio(this, this, videoUri);
mBinding.ivPlayAudio.setImageResource(R.drawable.pauseicon_small);
setSaveButtonClickable(false);
setCrossIconClickable(false);
setPlayIconClickable(true);
mBinding.rlRecording.setClickable(false);
mBinding.rippleBackground.startRippleAnimation();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
#TargetApi(Build.VERSION_CODES.N)
private void pauseRecording() {
if (mRecorder == null) {
return;
}
try {
mRecorder.pause();
mPauseTime=SystemClock.elapsedRealtime();
mAudioState.set(AudioRecordingEnum.AUDIO_PAUSE_STATE);
mBinding.tvStartRecording.setText(getResources().getString(R.string.txt_recording_is_paused));
mHandler.removeCallbacks(mTickExecutor);
whenRecordingIsPausedOrStopped();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
#TargetApi(Build.VERSION_CODES.N)
private void resumeRecording() {
if (mRecorder == null) {
return;
}
try {
mRecorder.resume();
mStartTime = (SystemClock.elapsedRealtime() - mPauseTime) + mStartTime;
mHandler.postDelayed(mTickExecutor, 1000);
mAudioState.set(AudioRecordingEnum.AUDIO_RECORDING_STATE);
mBinding.tvStartRecording.setText(getResources().getString(R.string.txt_recording));
whenRecordingIsInStartState();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
private boolean isBuildVersionIsGreaterOrEqualN() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
return true;
} else {
return false;
}
}
private void pauseStopRecording() {
if (isBuildVersionIsGreaterOrEqualN()) {
pauseRecording();
} else {
stopRecording();
}
}
private void startRecording() {
whenRecordingIsInStartState();
mOutputFile = getOutputFile();
mOutputFile.getParentFile().mkdirs();
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mOutputFile.getAbsolutePath());
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setAudioEncodingBitRate(48000);
mRecorder.setAudioSamplingRate(16000);
mRecorder.setMaxDuration((mMaxAudioTime * 1000));
mRecorder.setOnInfoListener(this);
try {
mRecorder.prepare();
mRecorder.start();
mStartTime = SystemClock.elapsedRealtime();
mHandler.postDelayed(mTickExecutor, 1000);
LOGGER.debug("Voice Recorder", "started recording to " + mOutputFile.getAbsolutePath());
} catch (IOException e) {
LOGGER.error("Voice Recorder", "prepare() failed " + e.getMessage());
}
}
private void whenRecordingIsInStartState() {
mAudioState.set(AudioRecordingEnum.AUDIO_RECORDING_STATE);
setPlayIconClickable(false);
setCrossIconClickable(false);
mBinding.tvStartRecording.setText(getResources().getString(R.string.txt_recording));
mBinding.ivRecord.setImageResource(R.drawable.pauseicon);
setSaveButtonClickable(false);
}
private void setSaveButtonClickable(boolean isClickable) {
if (isClickable) {
mBinding.tvSave.setAlpha(1.0f);
mBinding.tvSave.setClickable(true);
mBinding.tvSave.setTextColor(ContextCompat.getColor(this, R.color.colorAccent));
} else {
mBinding.tvSave.setAlpha(0.5f);
mBinding.tvSave.setClickable(false);
mBinding.tvSave.setTextColor(ContextCompat.getColor(this, R.color.colorMediumText));
}
}
private File getOutputFile() {
return new File(mAudioPath);
}
protected void stopRecording() {
mAudioState.set(AudioRecordingEnum.AUDIO_STOP_STATE);
mBinding.tvStartRecording.setText(getResources().getString(R.string.txt_recording_is_stopped));
whenRecordingIsPausedOrStopped();
mRecorder.stop();
mRecorder.release();
mStartTime = 0;
mPauseTime=0;
mRecorder = null;
mHandler.removeCallbacks(mTickExecutor);
}
private void whenRecordingIsPausedOrStopped() {
setPlayIconClickable(true);
setCrossIconClickable(true);
mBinding.ivRecord.setImageResource(R.drawable.audio_recording);
setSaveButtonClickable(true);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
AppUtils.showShortSnackBar(mBinding.tvSave, R.string.err_permission_denied);
return;
}
}
switch (requestCode) {
case PermissionUtils.RC_REQUEST_PERMISSION_RECORD_AUDIO:
startRecording();
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void setPlayIconClickable(boolean isVisible) {
if (isVisible) {
mBinding.ivPlayAudio.setClickable(true);
mBinding.ivPlayAudio.setAlpha(1.0f);
} else {
mBinding.ivPlayAudio.setAlpha(0.5f);
mBinding.ivPlayAudio.setClickable(false);
}
}
private void setCrossIconClickable(boolean isVisible) {
if (isVisible) {
mBinding.ivAudioDelete.setClickable(true);
mBinding.ivAudioDelete.setAlpha(1.0f);
} else {
mBinding.ivAudioDelete.setAlpha(0.5f);
mBinding.ivAudioDelete.setClickable(false);
}
}
#Override
public void onYesClicked() {
deleteRecording();
}
#Override
public void onVoiceComplete() {
mBinding.ivPlayAudio.setImageResource(R.drawable.play_after_recording_icon);
setCrossIconClickable(true);
setSaveButtonClickable(true);
setPlayIconClickable(true);
mBinding.rlRecording.setClickable(true);
mBinding.rippleBackground.stopRippleAnimation();
}
#Override
public void onBackPressed() {
if (mAudioState.get() == AudioRecordingEnum.AUDIO_RECORDING_STATE) {
mAudioManager.killMediaPlayer();
finish();
} else if (mAudioState.get() == AudioRecordingEnum.AUDIO_STOP_STATE) {
AppDialog.showCancelRecordingDialog(this, this);
} else {
finish();
}
}
#Override
public void onInfo(MediaRecorder mediaRecorder, int i, int i1) {
if (i == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
LOGGER.debug("AUDIOCAPTURE", "Maximum Duration Reached");
stopRecording();
}
}
#Override
protected void onPause() {
if (mAudioManager.isPlaying()) {
//PlayAudioManager.killMediaPlayer();
}
super.onPause();
}
#Override
public void onYesDiscardClicked() {
startRecording();
}
#Override
public void onDeleteRecording() {
AppUtils.deleteFile(mAudioPath);
finish();
}
/**
* this method will be called when any interrupt happens or home button is pressed
*/
#Override
protected void onUserLeaveHint() {
if (mRecorder != null && mAudioState.get() == AudioRecordingEnum.AUDIO_RECORDING_STATE) {
stopRecording();
}
if (mAudioManager.isPlaying()) {
//PlayAudioManager.killMediaPlayer();
}
super.onUserLeaveHint();
}
}
Below is Audio Playing class
public class PlayAudioManager {
private MediaPlayer mediaPlayer;
private IVoiceCompleteListener iVoiceCompleteListener;
public PlayAudioManager() {
}
public void playAudio(IVoiceCompleteListener listener, final Context context, Uri uri) throws Exception {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, uri);
}
iVoiceCompleteListener = listener;
mediaPlayer.setOnCompletionListener(
mp -> killMediaPlayer());
mediaPlayer.start();
}
public void pauseMediaPlayer() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
}
public void playMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
if (iVoiceCompleteListener != null) {
iVoiceCompleteListener.onVoiceComplete();
}
}
public boolean isPlaying() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
killMediaPlayer();
return true;
}
return false;
}
public boolean isMediaPlayerPlaying() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
return true;
}
return false;
}
public interface IVoiceCompleteListener {
void onVoiceComplete();
}
}

Porgress bar is running faster on every onClick

I'm trying to make a simple audio recorder. The problem with the audio recorder is that,every time the progress bar gets faster. It would run fine on the first turn, but if you cancel the audio and want to go the second time, it gets faster.
recordButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recorder == null) {
recorder = new MediaRecorder();
}
stopped=false;
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile("/sdcard/sample.3gp");
recorder.setMaxDuration(MAX_DURATION);
//Progressbar
pb.setMax(MAX_DURATION);
pb.setProgressTintList(ColorStateList.valueOf(Color.WHITE));
new CountDownTimer(MAX_DURATION, 250) {
public void onTick(long millisUntilFinished) {
pb.setProgress(pb.getProgress() + 250);
}
public void onFinish() {
}
}.start();
All of this is happening within a dialog, so how do I clear the dialog's contents so that the progress bar goes back to its default value.
long timestamp = DateUtils.getCurrentTimeMillis();
String imagePath = Environment.getExternalStorageDirectory() + "/testing/" + timestamp + "_D_FM_" + "John" + ".mp3";
MediaRecorder mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION); mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(imagePath);
mRecorder.setAudioEncodingBitRate(16);
mRecorder.setAudioSamplingRate(44100);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
// Starting record time
recordTime = 0;
// Show TextView that displays record time
try {
mRecorder.prepare();
mRecorder.start();
// Change isRecroding flag to true
isRecording = true;
handler.post(UpdateRecordTime);
} catch (IOException e) {
FRLog.e("LOG_TAG", "prepare failed", e);
}
When click audio playing:
private MediaPlayer mPlayer;
private void playAudio(final SeekBar audioSeekbar, int position, final ImageButton audioplayImgBtn, String fileName) {
seekBar = audioSeekbar;
if (audio_playing && audio_position == position) {
if (isPaused) {
mPlayer.start();
handler.post(UpdatePlayTime);
audioplayImgBtn.setImageResource(R.drawable.ic_pause);
isPaused = false;
} else {
mPlayer.pause();
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
isPaused = true;
}
} else {
if (audio_playing && audio_position != position) {
mPlayer.pause();
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
isPaused = true;
}
audio_position = position;
audioSeekbar.setProgress(0);
audioplayImgBtn.setImageResource(R.drawable.ic_pause);
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.stop();
mPlayer.reset();
mPlayer.release();
mPlayer = null;
} else {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
}
}
mPlayer = new MediaPlayer();
playTime = 0;
handler = new Handler();
// Reset max and progress of the SeekBar
try {
// Initialize the player and start playing the audio
mPlayer.setDataSource(Environment.getExternalStorageDirectory() + "/testing/" + fileName);
mPlayer.prepare();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
audioSeekbar.setMax(mPlayer.getDuration());
mPlayer.start();
audio_playing = true;
handler.post(UpdatePlayTime);
}
});
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
audioplayImgBtn.setImageResource(R.drawable.ic_messages_audio_play);
audioSeekbar.setProgress(0);
audio_playing = false;
handler.removeCallbacksAndMessages(null);
}
});
// Post the play progress
// updated code by manikandan
audioSeekbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
mPlayer.seekTo(sb.getProgress());
}
return false;
}
});
audioSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean fromUser) {
if (mPlayer != null && fromUser) {
mPlayer.seekTo(seekBar.getProgress());
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
mPlayer.seekTo(seekBar.getProgress());
}
}
}
});
} catch (IOException e) {
FRLog.e("LOG_TAG", "prepare failed", e);
}
}
}
Runnable UpdatePlayTime = new Runnable() {
public void run() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
handler.postDelayed(this, 500);
}
}
}
};

App relaunch state after pressing home button with videoview

I have a video player, when I start it and press launcher icon and again relaunch the app the video start playing from where it was.when I pause the video and press launcher icon and again relaunch the application.video is not in pause state. It again starts from last position.Thanks in advance
public class VideoFullscreenActivity extends Activity {
private static boolean startFromZero = false;
VideoView videoView;
private static boolean isplaying = false;
ProgressDialog pDialog;
SharedPreferences.Editor editor;
SharedPreferences prefs;
int restoredPosition;
public static boolean isStartFromZero() {
return startFromZero;
}
public static void setStartFromZero(boolean startFromZero) {
VideoFullscreenActivity.startFromZero = startFromZero;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_fullscreen);
videoView = (VideoView) findViewById(R.id.videoview);
editor = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE).edit();
prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
if (startFromZero) {
editor.putInt("CURRENT_POSITION", 0);//stopPosition is an int
editor.commit();
} else {
setStartFromZero(false);
}
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
if (Utilities.checkInternetConnection(this)) {
Intent intent = getIntent();
pDialog = new ProgressDialog(this);
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// Show progressbar
pDialog.show();
MediaController mediaController = new
MediaController(this);
mediaController.setAnchorView(videoView);
videoView.setMediaController(mediaController);
if(intent.getStringExtra(Constants.URL)!= null)
{
Uri videoUri = Uri.parse(intent.getStringExtra(Constants.URL));
videoView.setVideoURI(videoUri);
} else if (intent.getStringExtra("VideoUrl") != null)
{
Map<String, String> headers = new HashMap();
headers.put(APP_KEY, APPKEY_VALUE);
headers.put(SESSION_ID, SharedInstance.getInstance().getLoginDetails().getSessionId());
Uri uri = Uri.parse(intent.getStringExtra("VideoUrl"));
Method setVideoURIMethod = null;
try {
setVideoURIMethod = videoView.getClass().getMethod("setVideoURI", Uri.class, Map.class);
setVideoURIMethod.invoke(videoView, uri,headers);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//videoView.setVideoURI(uri,headers);
}
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
videoView.start();
}
});
if (prefs != null) {
restoredPosition = prefs.getInt("CURRENT_POSITION", 0); //0 is the default value.
}
videoView.seekTo(restoredPosition);
videoView.start();
Log.i("positionPlayback", "onCreate " + restoredPosition);
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
onBackPressed();
}
});
//---------------------------------------------------------------//
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
this.onPrepared(mediaPlayer);
}
});
}
#Override
public void onPause() {
super.onPause();
Log.i("positionPlayback", "onPause " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
}
restoredPosition = videoView.getCurrentPosition();
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
Utilities.hideKeybord(VideoFullscreenActivity.this);
}
#Override
public void onResume() {
super.onResume();
checkForCrashes();
startFromZero = false;
if (Utilities.checkInternetConnection(this)) {
Log.i("positionPlayback", "onResume " + restoredPosition);
pDialog.show();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
videoView.seekTo(restoredPosition);
videoView.start();
}
});
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void checkForCrashes() {
CrashManager.register(this, BuildConfig.hockeyAppId);
}
#Override
protected void onStart() {
super.onStart();
if (prefs != null) {
SharedPreferences prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
restoredPosition = prefs.getInt("CURRENT_POSITION", 0); //0 is the default value.
}
videoView.seekTo(restoredPosition);
videoView.start();
Log.i("positionPlayback", "onStart " + restoredPosition);
}
#Override
protected void onStop() {
super.onStop();
Log.i("positionPlayback", "onStop 1 " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
}
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
editor.commit();
Log.i("positionPlayback", "onStop " + restoredPosition);
}
#Override
protected void onDestroy() {
editor.putInt("CURRENT_POSITION", restoredPosition);
editor.commit();
Log.i("positionPlayback", "onDestroy " + restoredPosition);
super.onDestroy();
}
#Override
protected void onRestart() {
super.onRestart();
SharedPreferences prefs = getSharedPreferences("VIDEO_POSITION", MODE_PRIVATE);
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
Log.i("positionPlayback", "onRestart " + restoredPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
editor.putInt("CURRENT_POSITION", 0);
editor.commit();
finish();
}
}
Please try to make one status boolean to check video is manual pause or not.
boolean manual_pause = false;
in onPause check video status to affect on manual_pause.
#Override
public void onPause() {
super.onPause();
Log.i("positionPlayback", "onPause " + restoredPosition);
if (videoView != null && videoView.isPlaying()) {
videoView.pause();
manual_pause = false;
} else if(videoView != null){
manual_pause = true;
}
restoredPosition = videoView.getCurrentPosition();
editor.putInt("CURRENT_POSITION", restoredPosition);//stopPosition is an int
Utilities.hideKeybord(VideoFullscreenActivity.this);
}
than check this status in onResume() to set video status previously.
#Override
public void onResume() {
super.onResume();
checkForCrashes();
startFromZero = false;
if (Utilities.checkInternetConnection(this)) {
Log.i("positionPlayback", "onResume " + restoredPosition);
pDialog.show();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
restoredPosition = prefs.getInt("CURRENT_POSITION", 0);
videoView.seekTo(restoredPosition);
if(manual_pause) {
videoView.pause();
manual_pause = false;
}else{
videoView.start();
}
}
});
} else {
Utilities.showAlertLoginDialog(this, "", getResources().getString(R.string.internet_unavailable_msg));
}
}
You have to handle your previous status like this manualy.
Hope this will help you...
you are missing editor.commit(); # onPause you need to commit after you add a value!

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()

android - videoView does AsyncTask only once / onPostExecute never gets called

I have 3 videos. depending on the videoLong I play the selected video with videoView.
I have 2 questions:
The first time a video is played it works. The video stops at the correct time and finish() is used. BUT any time after that doInBackground doesnt check the other if statements.
My onPostExecute never gets called.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (videoLong == 0) {
videoView
.setVideoURI(Uri
.parse("http://pv...70ab1aae7633.mp4"));
videoView.seekTo(60000 * 10);// 10 mins
videoView.start();
new myAsync().execute();
} else if (videoLong == 1) {
videoView
.setVideoURI(Uri
.parse("http://pv....mp4"));
videoView.seekTo(60000 * 10);// 10 mins
videoView.start();
new myAsync().execute();
} else if (videoLong == 2) {
videoView
.setVideoURI(Uri
.parse("http://pv....mp4"));
videoView.seekTo(60000 * 10);// 10 mins
new myAsync().execute();
videoView.start();
}
}
private class myAsync extends AsyncTask<Void, Integer, Void> {
int duration = 0;
int current = 0;
protected void onPreExecute() {
super.onPreExecute();
System.out.println("on pre execute");
// alertDialog = new AlertDialog.Builder(PlayVideoActivity.this);
}
#Override
protected Void doInBackground(Void... params) {
videoView
.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
duration = videoView.getDuration();
}
});
videoView
.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// Do whatever u need to do here
System.out.println("video complete");
finish();
}
});
do {
current = videoView.getCurrentPosition();
// System.out.println("duration - " + duration + " current- " +
// current);
try {
publishProgress((int) (current * 100 / duration));
// System.out.println("time: " + current);
if (current >= 610100 && videoLong == 0) {
System.out.println("video 1 done");
videoView.stopPlayback();
videoView = null;
}
if (current >= 610200 && videoLong == 1) {
System.out.println("video 2 done");
videoView.stopPlayback();
finish();
}
if (current >= 610200 && videoLong == 2) {
System.out.println("video 3 done");
videoView.stopPlayback();
finish();
}
if (mProgressBar.getProgress() >= 100) {
// System.out.println("error100");
}
} catch (Exception e) {
// e.printStackTrace();
}
} while (mProgressBar.getProgress() <= 100);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
// System.out.println("values: " + values[0]);
mProgressBar.setProgress(values[0]);
}
#Override
protected void onPostExecute(Void result) {
System.out.println("on POST execute");
}
}
#Override
public void onBackPressed() {
if (videoView != null)
videoView.stopPlayback();
videoView = null;
System.out.println("back button pressed. stop playback");
super.onBackPressed();
}
Thanks for looking!

Categories

Resources