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().
Related
**
I am developing an media player streaming app.. While playing song the
seekbar is moving according to the song. But onTouching seek bar it is
not playing from the touched position..
**
My Java Code is As Folows...
public class Player extends Activity implements View.OnTouchListener,MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener {
private ImageButton btnPlay;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private SeekBar songProgressBar;
private int mediaFileLengthInMilliseconds;
private final Handler handler = new Handler();
String AudioURL = "http://f23.wapka-files.com/download/9/e/9/1408248_9e9b050b4bea1c48ba6b7329.mp3/bed5656a469655b9f12e/08-Chundari.Penne-Dulquer.Salmaan.mp3";
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
//-=------------------------------------------------------------
final ImageView iv = (ImageView) findViewById(R.id.image);
final String imgURL = "https://i.ytimg.com/vi/NLQHBv6lgXE/maxresdefault.jpg";
new DownLoadImageTask(iv).execute(imgURL);
//---------------------------------------------------
// All player buttons
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
//btnForward = (ImageButton) findViewById(R.id.btnForward);
//btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnNext = (ImageButton) findViewById(R.id.btnNext);
btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songProgressBar.setMax(99); // It means 100% .0-99
songProgressBar.setOnTouchListener(null);
mp = new MediaPlayer();
// Mediaplayer
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnBufferingUpdateListener(null);
mp.setOnCompletionListener(null);
try {
} catch (Exception h) {
Toast.makeText(Player.this, "NO MUSIC HERE...........", Toast.LENGTH_SHORT).show();
}
}
private void primarySeekBarProgressUpdater() {
songProgressBar.setProgress((int) (((float) mp.getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This math construction give a percentage of "was playing"/"song length"
if (mp.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(notification, 1000);
}
}
public void clik(View view){
try {
mp.setDataSource(AudioURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mp.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mp.getDuration(); // gets the song length in milliseconds from URL
if (!mp.isPlaying()) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
} else {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
primarySeekBarProgressUpdater();
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
songProgressBar.setSecondaryProgress(i);
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mp.stop();
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
// Log.d(TAG, "Moved , process data, Moved to :" + seekBarProgress.getProgress());
songProgressBar.setProgress(songProgressBar.getProgress());
return false;
}
// Log.d(TAG, "Touched , Progress :" + seekBarProgress.getProgress());
return true;
}
}
Please Help.....
Maybe you forgot set the position on the MediaPlayer with seekTo(int) method once the seekbar has moved. For example:
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(motionEvent.getAction() == MotionEvent.ACTION_MOVE){
songProgressBar.setProgress(songProgressBar.getProgress());
//seek to the position toucehd
mp.seekTo(songProgressBar.getProgress());
return false;
}
// Log.d(TAG, "Touched , Progress :" + seekBarProgress.getProgress());
return true;
}
You are setting the songProgressBar.setMax(99); max to 99 set it to mp total duration then seekbar will seek media player.
Add this line as shown in code
songProgressBar.setMax(mediaFileLengthInMilliseconds);
public void clik(View view){
try {
mp.setDataSource(AudioURL); // setup song from http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3 URL to mediaplayer data source
mp.prepare(); // you must call this method after setup the datasource in setDataSource method. After calling prepare() the instance of MediaPlayer starts load data from URL to internal buffer.
} catch (Exception e) {
e.printStackTrace();
}
mediaFileLengthInMilliseconds = mp.getDuration(); // gets the song length in milliseconds from URL
// Add this line here
songProgressBar.setMax(mediaFileLengthInMilliseconds);
if (!mp.isPlaying()) {
mp.start();
btnPlay.setImageResource(R.drawable.btn_pause);
} else {
mp.pause();
btnPlay.setImageResource(R.drawable.btn_play);
}
primarySeekBarProgressUpdater();
}
public class PlayerScreen extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private MediaPlayer mp;
private Button buttonplaypause;
private int count;
private SeekBar seekbar;
private int curpos, prevpos;
private Bundle b;
private String title;
private final Handler handler = new Handler();
private Runnable updatePositionRunnable = new Runnable() {
public void run() {
seekbar.setProgress(mp.getCurrentPosition());
handler.postDelayed(this, 6000);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_screen);
title = b.getString("title");
mp = new MediaPlayer();
try {
Log.d("message", "message");
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/"+title);
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//mp = MediaPlayer.create(this, R.raw.audio);
buttonplaypause = (Button) findViewById(R.id.buttonPlayPause);
seekbar = (SeekBar) findViewById(R.id.seekBar);
seekbar.setMax(mp.getDuration());
buttonplaypause.setBackgroundResource(R.drawable.play);
seekbar.setOnSeekBarChangeListener(this);
handler.postDelayed(updatePositionRunnable, 6000);
}
public void onProgressChanged(SeekBar mySeekBar, int progress, boolean fromUser) {
if (mp.isPlaying()) {
mp.seekTo(progress);
}
}
public void onStartTrackingTouch(SeekBar mySeekBar) {
}
public void onStopTrackingTouch(SeekBar mySeekBar) {
}
public void toPlayPause(View v) {
if (count % 2 == 0) {
buttonplaypause.setBackgroundResource(R.drawable.pause);
curpos = mp.getCurrentPosition();
prevpos = curpos;
mp.seekTo(curpos);
mp.start();
count++;
buttonplaypause.setBackgroundResource(R.drawable.play);
mp.pause();
count++;
}
}
}
What i'm trying to do is build a music player which displays the list of song in one activity in a List View and when the user taps on an item that particular song should be played in another intent (which is provided by play and pause button). The code provided above is the code for the second activity (the first part i.e. listing the songs is done). The first Activity passes the song title in a bundle which is received by this activity. I am new to android and don't know a lot about it. I don't know how to pass the song from one intent to another so that it is played. The problem I think is in the line setDataSource().
When the second Intent (i.e the code provided above) is opened on tapping item in the List View, the seek bar reaches it's end and no song is played
If there is any other, better way to pass the song from one intent to another feel free to describe it in detail.
When i play song in music player when i press a button i am forwarding the song for certain time,i am implementing this way,but i need when i press and hold the fast forward button wan to move the song means acting as our real music player,how can i am implementing please help me how i implement the fast forward button functionality is same as our music player fast forward button.
public class MainActivity extends Activity implements OnCompletionListener,
SeekBar.OnSeekBarChangeListener {
private ImageButton btnDecreaseSound, btnIncSound, btnReverse, btnPlay, btnForward,
btnPause;
private TextView currenttime, endtime;
private LinearLayout btnRedo, btnDelete;
private SeekBar songProgressBar;
private MediaPlayer mp;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private SeekBar volumeSeekbar ;
private AudioManager audioManager ;
private Handler mHandler = new Handler();
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Mediaplayer
mp = new MediaPlayer();
songManager = new SongsManager();
utils = new Utilities();
final SoundPool spool = null;
final int soundID = 0;
audioManager = (AudioManager) getSystemService(getApplicationContext().AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
// Listeners
songProgressBar.setOnSeekBarChangeListener(this); // Important
mp.setOnCompletionListener(this); // Important
// Getting all songs list
songsList = songManager.getPlayList();
// By default play first song
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
// Changing button image to play button
btnPlay.setImageResource(R.drawable.playbtn);
}
} else {
if (mp != null) {
mp.start();
//
btnPlay.setImageResource(R.drawable.pauseiconbtn);
}
}
}
});
volumeSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
btnReverse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// get current song position
int currentPosition = mp.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if (currentPosition - seekBackwardTime >= 0) {
// forward song
mp.seekTo(currentPosition - seekBackwardTime);
} else {
// backward to starting position
mp.seekTo(0);
}
}
});
btnForward.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int currentPosition = mp.getCurrentPosition();
// check if seekForward time is lesser than song duration
if (currentPosition + seekForwardTime <= mp.getDuration()) {
// forward song
mp.seekTo(currentPosition + seekForwardTime);
} else {
// forward to end position
mp.seekTo(mp.getDuration());
}
}
});
public void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsList.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
// Displaying Total Duration time
// endtime.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
currenttime
.setText("" + utils.milliSecondsToTimer(currentDuration));
//
String l = utils.milliSecondsToTimer(currentDuration);
String l2 = utils.milliSecondsToTimer(currentDuration);
long number = totalDuration - currentDuration;
String timechange = utils.milliSecondsToTimer(number);
System.out.println("l value: " + timechange);
endtime.setText("-" + timechange);
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration,
totalDuration));
// Log.d("Progress", ""+progress);
songProgressBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
}
/**
* When user starts moving the progress handler
* */
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
/**
* When user stops moving the progress hanlder
* */
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
// forward or backward to certain seconds
mp.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
/**
* On Song Playing completed if repeat is ON play same song again if shuffle
* is ON play random song
* */
#Override
public void onCompletion(MediaPlayer arg0) {
// check for repeat is ON or OFF
playSong(0);
currentSongIndex = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
}
you can not override Home button for your custom application. that is reserved. Please google it regarding overriding home button
Please go to this link\, you can get your answer here.
Android Overriding home key
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;
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);
}
});