I'm creating a recorder app with chronometer counter, the chronometer is working fine with start record, stop record and stop play.
My problem is only with start play, when pressing start play button, the chronometer start from 0 but I couldn't stop the chronometer when the audio file stops.
This is the start play code, please help. Any help I greatly appreciated
playAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
stopRecord.setEnabled(false);
startRecord.setEnabled(false);
stopAudio.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(AudioSavePathInDevice);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
if (!running) {
myChronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
myChronometer.start();
running = true;
// myChronometer.stop();
}
mediaPlayer.start();
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
Sir, this the code of stop audio
stopAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (running) {
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
pauseOffset = SystemClock.elapsedRealtime() - myChronometer.getBase();
running = false;
}
stopRecord.setEnabled(false);
startRecord.setEnabled(true);
stopAudio.setEnabled(false);
playAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
// MediaRecorderReady();
//resetmymyChronometer
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
}
}
});
this is the code of stop record
stopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (running) {
myChronometer.stop();
myChronometer.setBase(SystemClock.elapsedRealtime());
pauseOffset = 0;
pauseOffset = SystemClock.elapsedRealtime() - myChronometer.getBase();
running = false;
}
mediaRecorder.stop();
stopRecord.setEnabled(false);
playAudio.setEnabled(true);
startRecord.setEnabled(true);
stopAudio.setEnabled(false);
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
MediaRecorderReady method
public void MediaRecorderReady(){
//myChronometer start
if (!running) {
myChronometer.setBase(SystemClock.elapsedRealtime() - pauseOffset);
myChronometer.start();
running = true;
//***********************
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
}
startRecord Listener
startRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
startRecord.setEnabled(true);
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startRecord.setEnabled(false);
stopRecord.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
You can use OnCompletionListener, for example:
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// your code to stop record
}
});
for more information :
https://developer.android.com/reference/android/media/MediaPlayer.OnCompletionListener
The line
myChronometer.stop();
is never called.
In your playAudio's onClick() method, you should set
running = true
Related
Help me I am stuck on this, mediaPlayer.setDataSource() is giving error when clicking on any song list in recycler view. I am new to Android Studio as I have started it past year.
Here is the video of what is happening in my app
java.lang.IllegalStateException
at android.media.MediaPlayer._setDataSource(Native Method)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1296)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1279)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1261)
at android.media.MediaPlayer.attemptDataSource(MediaPlayer.java:1155)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1112)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:1019)
at com.example.musify.MainActivity$10.run(MainActivity.java:454)
at java.lang.Thread.run(Thread.java:919)**
Always getting error in onchanged method setDataSource:
#Override
public void onChanged(int position) {
currentSongNumber = position;
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_pause_24,currentSongNumber,musicLists.size()-1);
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
mediaPlayer.stop();
}
new Thread(new Runnable() {
#Override
public void run() {
try {
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//this is the place where i am getting error although i have reset on instance of mediaplayer
mediaPlayer.setDataSource(MainActivity.this, musicLists.get(currentSongNumber).getMusicFile());
MainActivity.this.runOnUiThread(() -> {
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
});
} catch (IOException e) {
new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(MainActivity.this, "Unable to Play Track!", Toast.LENGTH_SHORT).show());
e.printStackTrace();
}
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
final int getTotalDuration = mp.getDuration();
String generateDuration = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(getTotalDuration),
TimeUnit.MILLISECONDS.toSeconds(getTotalDuration)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getTotalDuration)));
endTime.setText(generateDuration);
isPlaying = true;
mp.start();
playSeekbar.setMax(getTotalDuration);
playpauseImage.setImageResource(R.drawable.pause_svg);
}
});
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
final int getCurrentDuration = mediaPlayer.getCurrentPosition();
String generateDuration = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(getCurrentDuration),
TimeUnit.MILLISECONDS.toSeconds(getCurrentDuration)-
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getCurrentDuration)));
playSeekbar.setProgress(getCurrentDuration);
startTime.setText(generateDuration);
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.reset();
String tm = "00:00";
startTime.setText(tm);
timer.purge();
timer.cancel();
isPlaying = false;
playpauseImage.setImageResource(R.drawable.ic_baseline_play_arrow_24);
playSeekbar.setProgress(0);
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(0);
// starts next music
onNext();
}
});
}
},1000,1000);
}
#Override
public void onPlay() {
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_pause_24,currentSongNumber,musicLists.size()-1);
isPlaying = true;
playpauseImage.setImageResource(R.drawable.pause_svg);
mediaPlayer.start();
musicLists.get(currentSongNumber).setPlaying(true);
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(currentSongNumber);
onChanged(currentSongNumber);
}
#Override
public void onPrev() {
int prevsongnumber = currentSongNumber-1;
if(prevsongnumber<0)
{
prevsongnumber = musicLists.size()-1;
}
CreateNotification.createNotification(MainActivity.this,musicLists.get(prevsongnumber),R.drawable.ic_baseline_pause_24,prevsongnumber,musicLists.size()-1);
musicLists.get(currentSongNumber).setPlaying(false);
musicLists.get(prevsongnumber).setPlaying(true);
musicbar_name.setText(musicLists.get(prevsongnumber).getTitle());
// musicbar_artist.setText(musicLists.get(prevsongnumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(prevsongnumber);
onChanged(prevsongnumber);
}
#Override
public void onPaused() {
CreateNotification.createNotification(MainActivity.this,musicLists.get(currentSongNumber),R.drawable.ic_baseline_play_arrow_24,currentSongNumber,musicLists.size()-1);
isPlaying = false;
mediaPlayer.pause();
playpauseImage.setImageResource(R.drawable.ic_baseline_play_arrow_24);
}
#Override
public void onNext() {
int nextsongnumber = currentSongNumber+1;
if(nextsongnumber>=musicLists.size())
{
nextsongnumber = 0;
}
CreateNotification.createNotification(MainActivity.this,musicLists.get(nextsongnumber),R.drawable.ic_baseline_pause_24,nextsongnumber,musicLists.size()-1);
musicLists.get(currentSongNumber).setPlaying(false);
musicLists.get(nextsongnumber).setPlaying(true);
musicbar_name.setText(musicLists.get(nextsongnumber).getTitle());
// musicbar_artist.setText(musicLists.get(nextsongnumber).getArtist());
musicAdapater.update(musicLists);
musicRecyclerV.scrollToPosition(nextsongnumber);
onChanged(nextsongnumber);
}
MediaPlayer.create() is better than setDatasource
got this from a YouTube comment!!
if(mediaPlayer.isPlaying())
{
mediaPlayer.pause();
}
mediaPlayer.stop();
mediaPlayer.release();
// passing applicationContext() and uri file of currentsongnumber
mediaPlayer = MediaPlayer.create(MainActivity.this, musicLists.get(currentSongNumber).getMusicFile());
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
MainActivity.this.runOnUiThread(() -> {
// musicbar_artist.setText(musicLists.get(currentSongNumber).getArtist());
musicbar_name.setText(musicLists.get(currentSongNumber).getTitle());
});
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I'm making an app that plays videos in a loop. It is supposed to play forever as long as the device is on. I have a list of videos in a variable and I use index to loop through every video to play it. The app works fine but when it runs for many hours (more than 20hrs) at a certain point the videoView freezes on a single frame and it won't call onCompletion or onError listeners. I run this on devices with API 17 and API 19. They both get the same error.
Here is my code (two methods that do the play loop):
public void playNextVideo(){
if(playIndex < 0) { playIndex = 0; }
if(allPromos.size() > 0) {
try {
Promo p = allPromos.get(playIndex);
playVideo(p);
} catch (IndexOutOfBoundsException e) {
Log.w("EXCEPTION", e);
isPlaying = false;
} finally {
playIndex++;
if (playIndex >= allPromos.size()) {
playIndex = 0;
}
}
} else {
Log.d("PlayNextVideo", "No videos in the playlist");
}
}
public void playVideo(Promo promo) {
File videoFile = new File(promo.getLocal_link());
if (!videoFile.exists()) {
Log.d("VIDEOPLAYER", "Video " + playIndex + " Has been skipped. File not found");
playNextVideo();
} else {
if (videoView.isPlaying()) {
videoView.stopPlayback();
}
videoView.setVideoPath(promo.getLocal_link());
videoView.requestFocus();
videoView.start();
videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(false);
}
});
videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
videoView.stopPlayback();
playNextVideo();
}
});
videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d("MEDIA PLAYER ERROR", what + ", " + extra);
videoView.stopPlayback();
try{
mp.release();
} catch (Exception e) {
Log.w("RELEASE EXCEPTION", e);
}
playNextVideo();
return true;
}
});
}
}
For an assignment I am trying to play songs from an array using media player. The first song in the array plays fine, but the next, and last track buttons are where my issue is. Could anyone suggest a way of playing the next/last song from my music array?
None relevant code not included.
// Arrays of sound files
private int[] audioFileArrayChill = {R.raw.vanilla_summer, R.raw.lifeline, R.raw.remember_the_mountain_bed};`
// Listen for the end of the track
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
for (int x = 1; x <= audioArray.length; x++) {
currentIndex++;
// Play next song in array
mp.selectTrack(audioArray[x]);
mp.start();
}
}
});
// Assigning onClickListener to last track button
lastTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.reset();
mediaPlayer.selectTrack(audioArray[currentIndex - 1]);
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("Error", "ERROR");
}
}
});
// Assigning onClickListener to next track button
nextTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.reset();
mediaPlayer.selectTrack(audioArray[currentIndex + 1]);
try {
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e("Error", "ERROR");
}
}
});
use below code for next button click
nextTrack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
mp.reset();
mp.setDataSource(audioArray[currentIndex + 1]);
mp.prepare();
mp.start();
}
My application contains one mediaplayer with one (play/pause) button in audio.xml , but the problem is that I am not able to find right code to stop MediaPlayer before the page gets destroyed and because of that the app crashes when i log in audio page (xml) and quit without running mediaplayer , here is the code i used:
public class audio extends Langue implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
// private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
//stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
//stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
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);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.espoir);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("Play");
} else {
mp.start();
startMedia.setText("Pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
/* if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("Play");
seekBar.setProgress(0);
}
}
*/
}
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) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
// stop song
#Override
protected void onPause(){
super.onPause();
mp.stop();
finish();
}
}
Do something like this into the onPause() method for preventing crash
try{
mp.stop();
} catch(Exception e) {
}
finish();
I try to replay a sound when I click on a button. But I get the Error (-19, 0) (what ever this means^^)
My code:
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
What is my mistake?
I was getting the same problem, I solved it by adding the following code:
mp1 = MediaPlayer.create(sound.this, R.raw.pan1);
mp1.start();
mp1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
};
});
You need to release the previous media player before starting the new one.
Declare MediaPlayer as a instance variable and then:
mp = null;
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.start();
}
});
Or in your case, since you always play the same sound you don't need to release the player and create a new one, simply reuse the old one.
final MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.plop);
mp.prepare(); // Blocking method. Consider to use prepareAsync
final Button xxx = (Button)findViewById(R.id.xxx);
xxx.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
mp.start();
}
});
I sloved this problem by this code:
public static void playSound() {
mMediaPlayer = new MediaPlayer();
try {
AssetFileDescriptor afd = context.getAssets().openFd("type.mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
arg0.release();
}
});
} catch (IllegalArgumentException | IllegalStateException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
i hope to help you.