Porgress bar is running faster on every onClick - android

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);
}
}
}
};

Related

Show progress bar while loading audio file

I am fairly new to android development, so what I am trying to make is an app that can play audio from url,
I want to show progress bar while the audio file is loading from the web(some audio files are big over 15mb) How can I do that?
here is my audio play activity
public class AudioPlayerActivity extends AppCompatActivity {
String Content_id,audio_url;
AudioView audioView;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_player);
audio_url = getIntent().getStringExtra("audio_url");
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
audioView=(AudioView)findViewById(R.id.audioview);
//pDialog.setMessage("Please Wait...");
//showDialog();
try {
audioView.setDataSource(audio_url);
audioView.start();
} catch (IOException e) {
e.printStackTrace();
}
//hideDialog();
}
#SuppressLint("MissingSuperCall")
#Override
protected void onStop() {
super.onPause();
audioView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
audioView.pause();
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
I am sharing the whole code for a well customized MediaPlayer. Just follow and implement this -
public class MusicActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener, SeekBar.OnSeekBarChangeListener {
private ImageView cross, settings;
private TextView titleText;
private RecyclerView recyclerView;
private ProgressBar mProgressBar;
private String id;
private String title;
private String audio;
private String english;
private String transliteration;
private String urdu;
private LinearLayoutManager linearLayoutManager;
private ProgressDialog progressDialog;
private float scrollTo;
private ImageView play_button;
private View view;
private TextView audiotitle;
private LinearLayout hide;
private ImageView play, rewind, forward;
private TextView currentTime, endTime;
private SeekBar seekbar;
private RelativeLayout progress_layout;
private LinearLayout offline_layout;
private ImageView download;
private ImageView cancel;
private Dialog mBottomSheetDialog;
private MediaPlayer mp;
private Handler mHandler = new Handler();
private Util util;
private boolean flag = false;
private ProgressBar progressBar;
Boolean isInternetPresent = false;
ConnectionDetector cd;
private String open_download_string;
private ProgressBar mProgress;
private ArrayList<String> filePath = new ArrayList<String>();
private int seekForwardTime = 10 * 1000;
private int seekBackwardTime = 10 * 1000;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (mp != null) {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
endTime.setText(util.milliSecondsToTimer(totalDuration) + " min");
// Displaying time completed playing
currentTime.setText(util.milliSecondsToTimer(currentDuration) + " min");
// Updating progress bar
int progress = (int) (util.getProgressPercentage(currentDuration, totalDuration));
seekbar.setProgress(progress);
mHandler.postDelayed(this, 100);
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
mp = new MediaPlayer();
cross = (ImageView) findViewById(R.id.cross);
settings = (ImageView) findViewById(R.id.settings);
titleText = (TextView) findViewById(R.id.title);
play_button = (ImageView) findViewById(R.id.play_button);
setMusicPlayerWidgets();
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
title = bundle.getString(Constant.SONG_TITLE);
audio = bundle.getString(Constant.SONG_AUDIO);
/*mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer mp) {
play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}
}
});*/
/* play_button.setVisibility(View.VISIBLE);
if(mp.isPlaying()){
if(mp!=null){
play_button.setImageResource(R.drawable.pause);
}
}else{
play_button.setImageResource(R.drawable.play);
}*/
} else {
progressBar.setVisibility(View.GONE);
play_button.setVisibility(View.GONE);
}
titleText.setText(title);
}
}
#Override
public void onResume() {
super.onResume();
setUpMusicPlayer();
}
/**
* MUSIC PLAYER IMPLEMENTATION
**/
private void setMusicPlayerWidgets() {
view = getLayoutInflater().inflate(R.layout.media_player_layout, null);
play = (ImageView) view.findViewById(R.id.play);
rewind = (ImageView) view.findViewById(R.id.rewind);
forward = (ImageView) view.findViewById(R.id.forward);
audiotitle = (TextView) view.findViewById(R.id.title);
hide = (LinearLayout) view.findViewById(R.id.hide);
seekbar = (SeekBar) view.findViewById(R.id.seekbar);
currentTime = (TextView) view.findViewById(R.id.time_current);
endTime = (TextView) view.findViewById(R.id.time_end);
progress_layout = (RelativeLayout) view.findViewById(R.id.progress_layout);
offline_layout = (LinearLayout) view.findViewById(R.id.offline_layout);
download = (ImageView) view.findViewById(R.id.download);
cancel = (ImageView) view.findViewById(R.id.cancel);
mBottomSheetDialog = new Dialog(DuaReadingsActivity.this, R.style.MaterialDialogSheet);
}
private void setUpMusicPlayer() {
audiotitle.setText(title);
seekbar.setOnSeekBarChangeListener(this);
mp.setOnCompletionListener(this);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
File dirFiles = DuaReadingsActivity.this.getFilesDir();
for (String strFile : dirFiles.list()) {
filePath.add(strFile);
}
if (!filePath.contains(open_download_string)) {
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
mediaBottomSheet();
}
}
});
}
private void mediaBottomSheet() {
mBottomSheetDialog.setContentView(view);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.show();
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
}
};
mBottomSheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// handler.removeCallbacks(runnable);
}
});
handler.postDelayed(runnable, 10000);
hide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBottomSheetDialog.dismiss();
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
rewind.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rewindSong();
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
forwardSong();
}
});
}
public void rewindSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition - seekBackwardTime >= 0) {
mp.seekTo(currentPosition - seekBackwardTime);
} else {
mp.seekTo(0);
}
}
}
public void forwardSong() {
if (mp != null) {
int currentPosition = mp.getCurrentPosition();
if (currentPosition + seekForwardTime <= mp.getDuration()) {
mp.seekTo(currentPosition + seekForwardTime);
} else {
mp.seekTo(mp.getDuration());
}
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
if (mBottomSheetDialog.isShowing()) {
mBottomSheetDialog.dismiss();
}
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.seekTo(0);
flag = false;
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
play_button.setImageResource(R.drawable.play);
play.setImageResource(R.drawable.play_button);
mp.pause();
}
} else {
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
if (flag == false) {
playSong();
flag = true;
} else {
mp.start();
}
}
}
});
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = util.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
public void playSong() {
try {
/*mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(audio);
mp.prepare();*/
mp.start();
play_button.setImageResource(R.drawable.pause);
play.setImageResource(R.drawable.pause_button);
seekbar.setProgress(0);
seekbar.setMax(100);
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} /*catch (IOException e) {
e.printStackTrace();
}*/
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onDestroy() {
super.onDestroy();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
mp.reset();
mp.prepareAsync();
mp.stop();
mp.release();
mp = null;
} catch (Exception e) {
e.printStackTrace();
}
final Handler handler = new Handler();
new Runnable() {
public void run() {
finish();
handler.postDelayed(this, 150);
}
};
if((mProgress != null) && (mProgress.getProgress() != 0)){
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
// finish();
}
#Override
protected void onPause() {
super.onPause();
if (mp.isPlaying()) {
mp.pause();
}
}
#Override
protected void onStop() {
super.onStop();
if (mp.isPlaying()) {
mp.pause();
}
}
private class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
mProgress = (ProgressBar) view.findViewById(R.id.circularProgressbar);
mProgress.setProgress(0);
mProgress.setSecondaryProgress(100);
mProgress.setMax(100);
mProgress.setIndeterminate(false);
mProgress.setProgressDrawable(getResources().getDrawable(R.drawable.download_progress));
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
FileOutputStream outputStream = openFileOutput(audio.substring(audio.lastIndexOf('/') + 1), Context.MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
outputStream.write(data, 0, count);
}
outputStream.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
getFilesDir().getAbsolutePath();
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.VISIBLE);
mProgress.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
mProgress.setProgress(progress[0]);
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.GONE);
download.setVisibility(View.VISIBLE);
offline_layout.setVisibility(View.GONE);
mProgress.setProgress(0);
DownloadFileFromURL.this.cancel(true);
File file = new File(DuaReadingsActivity.this.getFilesDir() + "/" +open_download_string);
file.delete();
if(file.exists()){
try {
file.getCanonicalFile().delete();
} catch (IOException e) {
e.printStackTrace();
}
if(file.exists()){
getApplicationContext().deleteFile(file.getName());
}
}
}
});
download.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
progress_layout.setVisibility(View.VISIBLE);
download.setVisibility(View.GONE);
offline_layout.setVisibility(View.GONE);
cd = new ConnectionDetector(DuaReadingsActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new DownloadFileFromURL().execute(audio);
} else {
cd.noInternetDialog();
}
}
});
}
}
}
This will work perfectly if you follow well. Cheers!!

Media player (-19,0) for playing lots of audio files from raw

I am plying all sounds from raw folder. Using playSound() and releasing sound after completion as well on error releasing sound. Still i am getting error(-19,0) after couple of sounds played using playSound().
public static MediaPlayer mediaPlayer;
public static boolean playSound(final Context context, int resId) {
if(releaseSound()){
mediaPlayer = MediaPlayer.create(context, resId);
mediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d("test", "Media player error :" + what + " extra:" + extra);
if(what == 19)
FireToast
.showToast(context,
"MediaPlayer error (Out of buffer). Please restart your application.");
releaseSound();
mp.release();
mp = null;
return false;
}
});
if (resId == 0) {
FireToast.showToast(context, "File not found");
return false;
}
// mediaPlayer = MediaPlayer.create(context, resId);
try {
if (mediaPlayer != null)
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseSound();
FireToast.showToast(context,"MediaPlayer song completed.");
}
});
mediaPlayer.start();
setPause(false);
return true;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static boolean releaseSound() {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
mediaPlayer = null;
isPause = false;
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}

Media Recorder record application audio

I have an application that has a few buttons that have sounds (soundPool) I need to write them down on a flash card I make it through the MediaRecorder but when I run the app and then turn on the record playing and click stop recording application crashes you do not tell me what the problem is?
I expect that in the method recordStop
public class MainActivity extends Activity {
int kickSound;
SoundPool mSoundPool;
AssetManager assets;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String fileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
kickSound = loadSound("snare_trap.ogg");
ImageButton kick = (ImageButton)this.findViewById(R.id.imageButton1);
kick.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN){
playSound(kickSound);
}
return false;
}
});
fileName = Environment.getExternalStorageDirectory() + "/record.3gpp";
}
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Couldn't load file '" + fileName + "'", Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
}
public void recordStart(View v) {
try {
releaseRecorder();
File outFile = new File(fileName);
if (outFile.exists()) {
outFile.delete();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(AudioManager.STREAM_MUSIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.setOutputFile(fileName);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void recordStop(View v) {
mediaRecorder.stop();
}
public void playStart(View v) {
try {
releasePlayer();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileName);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void playStop(View v) {
if (mediaPlayer != null) {
mediaPlayer.stop();
}
}
private void releaseRecorder() {
if (mediaRecorder != null) {
mediaRecorder.release();
mediaRecorder = null;
}
}
private void releasePlayer() {
mediaPlayer.release();
mediaPlayer = null;
}
#Override
protected void onDestroy() {
super.onDestroy();
releasePlayer();
releaseRecorder();
}
}
Why are you releasing the recorder to start out with? Releasing should only be used if you don't want to access the recorder anymore. Try moving the release to the end.

Pause playing record in android

I have a simple class to record voice and playing it after record play file:
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private Button startRecord, startPlaying, stopPlaying;
private MediaPlayer mPlayer = null;
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
//stopPlaying();
pausePlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void pausePlaying(){
mPlayer.stop();
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
startPlaying = (Button) findViewById(R.id.buttonStartPlay);
stopPlaying = (Button) findViewById(R.id.buttonStopPlaying);
startRecord = (Button) findViewById(R.id.buttonStartRecord);
startRecord.setOnClickListener(new OnClickListener() {
boolean mStartRecording = true;
#Override
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
startRecord.setText("Stop recording");
} else {
startRecord.setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
startPlaying.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onPlay(true);
}
});
stopPlaying.setOnClickListener(new OnClickListener() {
boolean mStartPlaying = true;
#Override
public void onClick(View v) {
onPlay(false);
}
});
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
I know how can I pause, but I don't know how can I run file again but from moment where I pause my file. Any ideas?
Change this :
private void pausePlaying(){
mPlayer.stop();
}
To:
private void pausePlaying(){
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
}
Don't use .stop() to pause. In the MediaPlayer API you can see that .pause() would be the best option. If you reorganized
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
To happen in your onCreate method you can avoid it resetting every time.
Check out their diagram http://i.stack.imgur.com/svHrq.gif

Android SeekBar: When setProgress then SeekBar progress is jumping to the beginning/middle/end

I have a problem of that how to setup seekbar to work correctly when I setProgress upon click. Progress is jumping to the beginning/middle/end depends on where I click on it. How is it possible to solve?
That my attemps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
....
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
seekBar.setMax(mp.getDuration());
System.out.println("curpos" + mp.getCurrentPosition());
new Thread(new Runnable() {
public void run() {
try {
while (mPlayer != null && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
Message msg = new Message();
int millis = mPlayer.getCurrentPosition();
msg.obj = millis / 1000;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("my Exception" + e);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
Full Code:
public class VideoPlayerActivity extends Activity implements Callback, OnSeekBarChangeListener, OnTouchListener, OnErrorListener, OnCompletionListener, OnPreparedListener {
MediaPlayer mPlayer;
AssetFileDescriptor afd;
VideoView videoView;
SurfaceHolder holder;
MediaController mController;
String videoPath;
SeekBar seekBar;
ImageButton mPlay, mStop, mPause;
TextView mCurDuration, mDuration;
int position = 0;
Handler handler = new Handler();
Runnable r;
boolean controlsVisibility = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mDuration = (TextView) findViewById(R.id.tvDuration);
mCurDuration = (TextView) findViewById(R.id.tvCurDuration);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setFocusable(false);
videoView.setOnTouchListener(this);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mStop = (ImageButton) findViewById(R.id.stop);
mController = new MediaController(this);
videoView.setMediaController(mController);
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Play:", " is Pressed!");
if (mPlayer == null)
playVideo();
mPlayer.start();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Pause:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
Log.e("mPlayer status: ", "Not Null");
if (mPlayer.isPlaying())
Log.e("mPlayer status: ", "Not Null");
mPlayer.pause();
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Stop:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
seekBar.setProgress(0);
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
});
}
private void playVideo() {
try {
if (afd != null && mPlayer != null) {
mPlayer.start();
return;
}
Log.e("VideoPath:", videoPath);
if (videoPath != "") {
afd = getAssets().openFd(videoPath);
// "videos/start.mp4"
mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setScreenOnWhilePlaying(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDisplay(holder);
mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mPlayer.prepare();
mPlayer.start();
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
}
} catch (IllegalArgumentException 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();
}
}
public void surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("Debug:", "onError---> what:" + what + " extra:" + extra);
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (controlsVisibility) {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
handler.removeCallbacks(r);
} else {
controlsVisibility = true;
mPlay.setVisibility(View.VISIBLE);
mPause.setVisibility(View.VISIBLE);
mStop.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
AutoHideControls();
}
return false;
}
public void AutoHideControls() {
r = new Runnable() {
public void run() {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
}
};
handler.removeCallbacks(r);
handler.postDelayed(r, 4000);
}
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Thread(new Runnable() {
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The same but throughtout AsyncTask (but the same result - still jumping):
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Async().execute();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
seekBar.setProgress(progress);
Log.e("SeekedProgressTime: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("SeekedProgressTime: ", Integer.toString(seekBar.getProgress()));
}
}
class Async extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
Log.e("Current mPlayer time in Thread: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("Current seekBar time in Thread: ", Integer.toString(seekBar.getProgress()));
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
} catch (Exception e) {
}
seekBar.setProgress(currentPosition);
}
return null;
}
}
Maybe, I did something wrong inside the AsyncTask, I cannot understand what is the problem with this seekBar. Check what real position it takes when you click somewhere on the seekbar, everything correct but in one moment its position value overrides somehow.

Categories

Resources