My ProgressBar does not reset after audio is done. I ask a question before on this and got it working but now just stopped working and not sure why it doesn't. Any help would be awesome.
All I want is it to chose a audio at random then play one and when finished you can press play again to listen to the same audio it chose at random.
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
//To update progress bar
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
You problem is mp.getDuration() is a milliseconds, which changes in each song. So don't use progressBar.setMax(mp.getDuration());. As it only works once for the very first song. Use progressBar.setMax(100); instead. Then use currentPosition= 100 * mp.getCurrentPosition() / mp.getDuration(); This should work fine.
Also don't forget adding progressBar.setProgress(0); when one song is finished or stop-button is clicked.
EDIT: Try resetting it inside of your completion listener. Scratch the setter then. Try using this:
Thread.sleep(1000);
currentPosition++;
Instead of this:
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
That is in your run() function. Then it will increment from 0 to total and you won't have to worry about getting or setting the currentposition, just the progress which is being done with the previous change below.
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
//Reset here
progressBar.setProgress(0);
}
});
Related
i am designing a mediaplayer from scratch so what i am getting stuck in is that when the song finish to play i want to set seekbar to initial value
i know this can be done with
seekBar.setProgress(0)
but this don't work with me and i want the play button to switch back to pause button and if the user play song again than the song will be played normally
here is my code of media player and hope you tell me what is the logic and how to place it
public class MusicPlayerActivity extends AppCompatActivity implements Runnable,
SeekBar.OnSeekBarChangeListener {
ImageView playpause;
SeekBar seekBar;
MediaPlayer mp = null;
int len = 0;
boolean isPlaying = false;
public MusicPlayerActivity() throws IOException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
String url = getIntent().getExtras().getString("musicurl");
playpause = (ImageView)findViewById(R.id.imageView);
seekBar = (SeekBar)findViewById(R.id.seekBar);
playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isPlaying){
playpause.setImageResource(R.drawable.pause);
mp.pause();
len = mp.getCurrentPosition();
seekBar.setEnabled(false);
}else{
playpause.setImageResource(R.drawable.play);
mp.seekTo(len);
mp.start();
seekBar.setEnabled(true);
}
isPlaying = !isPlaying;
}
});
mp = new MediaPlayer();
try {
mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//if(mp.isPlaying()) mp.stop(); mp.release();
mp.start();
seekBar.setMax(mp.getDuration());
new Thread(this).start();
// Toast.makeText(this, mp.getDuration(), Toast.LENGTH_SHORT).show();
}
//if(mp.isPlaying()){}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mp.stop();
startActivity(new Intent(this,MainActivity.class));
break;
}
return true;
}
#Override
public void onBackPressed() {
Intent mainActivity = new Intent(Intent.ACTION_MAIN);
mainActivity.addCategory(Intent.CATEGORY_HOME);
mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
}
You are not setting the listener : seekbar.setOnSeekBarChangeListener(this)
Add seekbar.setOnSeekBarChangeListener(this); in your onCreate otherwise the onProgressChanged() does not get called.
To reset progress bar look into the following approach:
Set OnCompletionListener on your media player instance. When the media file completes playing, your can carry out the required actions in OnCompletion(MediaPlayer mp) callback function.
Adding following code snippet before mp.start() should work for you.
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
seekBar.setProgress(0); // sets seekbar to initial position.
toggleViews();//implement this function to toggle your play/pause button
}
});
i create simple code with button and sound file (mp3) ,
now , when i am pressing at the button , the sound file is playing , but if i am pressing it several times (fast) , it just being playing for first click and till the mp3 ends...i want each click to play the sound from the beginning.
public class TrafficLightsActivity extends Activity implements OnClickListener {
private ImageButton Upbutton ;
private ImageButton Downbutton ;
private ImageView Image ;
private MediaPlayer mp1 ;
private MediaPlayer mp2 ;
int counter=5 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traffic_lights);
Upbutton = (ImageButton) findViewById (R.id.button1) ;
Downbutton = (ImageButton) findViewById (R.id.button2) ;
Image = (ImageView) findViewById(R.id.imageView1) ;
mp1 = MediaPlayer.create(this, R.raw.nextsound) ;
mp2 = MediaPlayer.create(this, R.raw.backsound) ;
Upbutton.setOnClickListener(this) ;
Downbutton.setOnClickListener(this) ; }
#Override
public void onClick(View v) {
if (Upbutton == v){
if (mp1.isPlaying()){
mp1.stop() ;
}
counter= counter+1 ;
System.out.println("Number of clicks is: " + counter) ;
mp1.start();
} }
You can call seekTo(0) method that will let to replay the sound from the start without finishing the sound:
if (Upbutton == v){
if(mp1.isPlaying())
mp1.seekTo(0);
mp1.start();
}
try this way
#Override
public void onClick(View v) {
if(mp1!=null){
try{
mediaPlayer.stop();
mediaPlayer=null;
mediaPlayer.release();
}
}
catch(IllegalStateException e){
//System.out.println(e);
}
catch(Exception e){
//System.out.println(e);
}
else{
mp1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
}
});
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
}
I have a button, when I click it plays music, how to do it, when I click second time, to stop the music?
Button two = (Button)this.findViewById(R.id.button2);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
two.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
mp2.start();
}
});
Ok, this one works:
Button one = (Button)this.findViewById(R.id.button1);
final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.n);
one.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp2.pause();
}
else {
mp2.start();
}
;
}});
The one with Pause above it works, but If I want to stop the music, it does not work.
Following not working:
#Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp2.stop();
}
else {
mp2.start();
}
;
}});
I get error: start called in state 0
error (-38, 0)
According to http://developer.android.com/reference/android/media/MediaPlayer.html, I suppose you could do something like this:
Button two = (Button)this.findViewById(R.id.button2);
final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);
two.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// If the music is playing
if(mp2.isPlaying() == true)
// Pause the music player
mp2.pause();
// If it's not playing
else
// Resume the music player
mp2.start();
}
});
You can actually write just
if(mp2.isPlaying())
instead of
if(mp2.isPlaying() == true)
It's just for the sake of understanding what is going on.
You could have a boolean check to see if it is started (and set the boolean to false) and if so stop the music, if not start it (and set the boolean to true). Something like:
public void onClick(View v)
{
if(musicPlaying == false)
{
mp2.start();
musicPlaying = true;
}
else
{
mp2.stop();
musicPlaying = false;
}
}
if(mp2.isPlaying()) {
mp2.pause();
} else {
mp2.start();
}
This is what I used to start and stop the music, you must prepare the MediaPlayer for playback. Note: this will start the music from where it stopped.Mediaplayer prepare() methodIf you are streaming music you should use prepareAsync ()
musicButton = (Button) findViewById(R.id.btn_dj_player);
musicButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {//check if a song is already playing
mp.stop();
try {
mp.prepare();//get the mediaplayer reeady for playback
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
mp.start();
}
}
});
If you have only one sound and you want it to start or stop with only one button than this may help .
Button button_name = (Button)this.findViewById(R.id.Your_button_id_Here);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.YOur_audio_File_name_here);
button_name.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
if(mp.isPlaying())
{
mp.pause();
}
else
{
mp.start();
}
}
});
Have you tried using the seekTo() function?
Something like:
if (mp.isPlaying()) {
mp.stop();
mp.prepareAsync();
mp.seekTo(0);
} else {
mp.start();
}
}
I am just guessing here, but might be worth looking into. :-)
I accomplished this as follows:
I declared a boolean variable:
boolean isButtonClicked = false;
Then I set up an if else in a method like so:
initPlaySound()
{
if(isButtonClicked)
{
player.start();
} else{
player.stop();
}
Lastly I set up an onClick of the button within the method:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
isButtonClicked = !isButtonClicked;
initPlaySound();
}
});
Basically, when the button is first clicked the boolean is set to the opposite of its' current state (false to true) and the code within the if executes. Once the button is clicked again the boolean is set to the opposite again (true to false) and the sound stops.
I solved this problem in a manual way. If sound is playing, i wrapped sound into beginning(seekTo(0)), then paused the sound. If sound is already paused, only seekTo(0) is called.
public void onClick(View v) {
if(mp.isPlaying()){
mp.seekTo(0);
mp.pause();
}
else{
mp.seekTo(0);
}
} ;
Add a global variable boolean flag=false;
if(flag==false)
{
mp=MediaPlayer.create(this, R.raw.abc);
mp.start();
playbutton.setText("Pause");
flag=true;
}
else if(mp.isPlaying()&&flag==true)
{
mp.pause();
playbutton.setText("Play");
flag=false;
}
This code will work if you want to use the same button as PLAY/PAUSE in your app. Hope this helps. Add this code in the button onClick() function which you are using to play or pause.
I have asked this question 2 times now still haven't got it to work. Any help would be awesome
My ProgressBar does not reset after audio is done, the bar just stays to the max blue line. I ask a question before on this and got it working but now just stopped working and not sure why it doesn't. Any help would be awesome.
All I want is it to chose a audio at random then play one and when finished you can press play again to listen to the same audio it chose at random.
Heres code:
public class player2 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_2);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound04; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound05; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound06;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(100);
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
I did not check all the code thoroughly, but at a quick glance I would guess that your thread (which updates the progress bar) is stopping at completion and you never start it again (ie. when the user clicks play again). Just try restarting the thread in your pauseicon.setOnClickListener (when playback is complete). Example:
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
// RESTART THE UPDATE THREAD //
new Thread(this).start();
}
}
});
EDIT using a static variable to store thread so that it can be restarted from the view's onClick method:
// add this to your class as a member
static Thread progressThread = new Thread(this);
// add this to BOTH onCreate and onClick
progressThread.start();
If this does not work (I can't test it out right now), you can simply keep the thread running, for example:
// flag to set when thread should be actively running
static boolean runThread = true;
// change your run method to something as follows
public void run() {
while ( runThread ) {
if ( mp != null && currentPosition <= total ) {
int currentPosition= 0;
int total = mp.getDuration();
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
else
Thread.sleep(1000);
}
}
// then when you no longer need to update the progress bar set the flag to false,
// which will cause your thread to finish. this can go anywhere, depending on
// your needs
runThread = false;
I've got it set up with a random sound playing onCreate and I have to add a seekbar to track the audio, it moves with track but will not go back if seekbar is pulled back to another part in the audio. Any help would be great, only beginner, sorry for being a noob :).
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private SeekBar songProgressBar;
private ImageButton playicon;
private ImageButton pauseicon;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private SeekBar seek;
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start();
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.pauseicon)
if(mp.isPlaying()){
mp.pause();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.playicon);
} else {
mp.start();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
songProgressBar.setProgress(currentPosition);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
The run() method is never called. Instead create a Handler object in the main thread (you did already but it is unused), remove the Thread.sleep() from the run method but add a call to postDelayed() method of the Handler at the end of run() (and maybe a condition to call it only while playing).
After starting playback, call run() method once (from main thread). It will then take care about calling itself subsequently with postDelayed().