Seekbar for mp3 from sd card - android

This code is to read a mp3 from raw folder,But I want to change my mp3 file to another file from sd card
its new code, music played but seekbar does not work properly, when i toch it seekbar come back to frist position
public class MainActivity extends Activity implements OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
MediaPlayer mediaPlayer;
TextView text_shown;
Handler seekHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException 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();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
}

Just move this line
seek_bar.setMax(mediaPlayer.getDuration());
to seekUpdation() after
seekHandler.postDelayed(run, 1000);

Replace
mediaPlayer = MediaPlayer.create(this, R.raw.my_file);
with:
String filePath = Environment.getExternalStorageDirectory() + "/randomDirectory/yourFile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();

Related

How to start MediaPlayer after it has been stopped in android

I am new to Android and in my app I am working with MediaPlayer.
When I first tap the start button, the song plays, but when I tap the stop button and then I tap on the start button again, the song does not start playing again. Here's what I have so far:
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Try this :
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
}
});
just check like this way
if(mdpl.isPlaying()){
mdpl.pause();
} else {
mdpl.start();
}
You can not call start, it media player in on stop state. Take a look on the state diagram of media player MediaPlayer state diagram.
When you call stop, you have to call release(), and with start you get a new media player, or just call reset.
try this
public void onStopBtnClick(View view) {
if (mAudioHelper != null) {
mAudioHelper.stop();
displayMessage("Stopping!");
}
}
Here is code to set sound file.
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = new MediaPlayer();
AppLog.d("Created new Media player");
try {
mPlayer.setDataSource(fileName);
} catch (IOException e) {
AppLog.e("Can't open " + fileName + " file", e);
}
Before playing u should call the mPlayer.prepareAsync() function.
if you want to pause/play you have to use this code:
if (mediaPlayer.isPlaying()){
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
If you want to stop player use this:
if (mPlayer != null){
mPlayer.stop();
mPlayer.release();
}
mPlayer = null;
If you want to start song again use first functions and next with this steps
This code may help you..
#Override
protected void onDestroy() {
super.onDestroy();
destroyMediaPlayer();
}
private void destroyMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
Log.d("here", "destroy");
} catch (Exception e) {
e.printStackTrace();
}
}
}
SOLUTION 1
for this solution, I took some info from here
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
MediaPlayer mp;
/**
* remain false till media is not completed, inside OnCompletionListener make it true.
*/
private boolean initialStage = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (initialStage) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
new Player()
.execute("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} else {
if (mp && !mp.isPlaying())
mp.start();
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp && mp.isPlaying())
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
mp.release();
mp = null;
initialStage = true;
}
}
});
}
/**
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
* #author piyush
*
*/
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mp.setDataSource(params[0]);
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
initialStage = true;
mp.stop();
mp.reset();
}
});
mp.prepare();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mp.start();
initialStage = false;
}
public Player() {
progress = new ProgressDialog(PlayngUrlFiles.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
this.progress.show();
}
}
}
SOLUTION 2
in order to avoid data downloding, try this
public class PlayngUrlFiles extends AppCompatActivity {
Button start, pause, stop;
boolean prepared;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playingurls_layout);
start = (Button) findViewById(R.id.button1);
pause = (Button) findViewById(R.id.button2);
stop = (Button) findViewById(R.id.button3);
final MediaPlayer mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
prepared = false;
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
prepared = true;
mp.start();
}
});
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
try {
if(!prepared) {
mp.prepareAsync();
prepared = true;
} else {
mp.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.pause();
}
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mp) {
mp.stop();
prepared = false;
}
}
});
}
}
#MRodrigues was right about media player states. But instead of calling release() after stop, Modify your code as below.
Currently,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
mp.prepare();
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.start();
}
});
modify to,
try {
mp.setDataSource("http://programmerguru.com/android-tutorial/wp-content/uploads/2013/04/hosannatelugu.mp3");
} catch (Exception e) {
e.printStackTrace();
}
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mp.isPlaying()) {
mp.prepare();
}
mp.start();
}
});

Seekbar not working

I found some code for a seekbar to work with a mediaplayer online:
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// remove message Handler from updating progress bar
mHandler.removeCallbacks(mUpdateTimeTask);
}
#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();
}
I get an error because of the Override's, telling me that they must override or implement a supertype method. When I remove them, my code compiles and runs but the seekbar has no affiliation with the music playing, as in I can move it around but the music keeps playing.
Thanks.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mp = new MediaPlayer();
seekBar = (SeekBar) findViewById(R.id.seekBar1);
seekBar.setOnSeekBarChangeListener(this); //this line causes an error
try {
mp.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath() + "/SpaceJam.mp3");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onStart(){
super.onStart();
btnPlay = (ImageButton) findViewById(R.id.play_pause);
btnStop = (ImageButton) findViewById(R.id.stop);
songTitleLabel = (TextView) findViewById(R.id.songname);
songTitleArtist = (TextView) findViewById(R.id.artist);
songCurrentDurationLabel = (TextView) findViewById(R.id.current);
songTotalDurationLabel = (TextView) findViewById(R.id.total);
albumArt = (ImageView) findViewById(R.id.albumArt);
res = getResources().getDrawable(R.drawable.album_art);
utils = new Utilities();
. . .
}
As prijupaul mentioned, you must to implement OnSeekBarChangeListener. change your code as follow:
public class MainActivity extends Activity implements OnSeekBarChangeListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
...
seekBar.setOnSeekBarChangeListener(this);
...
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}

Get time Elapsed and duration of MP3 file streaming android

When my mediaplayer starts playing, I want to get the time elapsed from the beginning of the player till the end of the media being played. For example 00:01, 00:02, 00:03, 00:04... How can i achieve this? Below is my mediaplayer class.
public class EntityPageActivity extends Activity implements Runnable, OnClickListener, OnSeekBarChangeListener{
private SeekBar seekBar;
private Button startMedia;
private Button pauseMedia;
private MediaPlayer mp;
Uri url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample);
AudioControl();
}
public void AudioControl(){
seekBar = (SeekBar) findViewById(R.id.seekBar);
startMedia = (Button) findViewById(R.id.play);
pauseMedia = (Button) findViewById(R.id.pause);
startMedia.setOnClickListener(this);
pauseMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
//System.out.println("maxvolume"+Integer.toString(maxVolume));
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
mp.seekTo(arg1);
seekBar.setProgress(arg1);
}
});
}
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;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp != null && mp.isPlaying()) return;
if(seekBar.getProgress() > 0) {
mp.start();
return;
}
mp = MediaPlayer.create(EntityPageActivity.this,Uri.parse("http://cdn-preview-e.deezer.com/stream/ed403858b3532e9c07c99d7015269848-2.mp3"));
mp.start();
seekBar.setProgress(0);
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
if (v.equals(pauseMedia) && mp!=null) {
mp.pause();
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Here are these two methods one is to get Media Player Current Position and second is to get total duration
// returns current position
mediaPlayer.getCurrentPosition();
//returns total duration
mediaPlayer.getDuration();
hope this will help
Implement a runnable when you start your mediaplayer:
mp.start();
Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
while (mp.isPlaying()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
seekbar.setMax(mp.getDuration() / 1000);
currTime.setText(getDurationString(mp
.getCurrentPosition() / 1000));
seekbar.setProgress(mp
.getCurrentPosition() / 1000);
}
});
}
}
};
new Thread(runnable).start();

Android mediaplayer with seekbar

How to use the seekbar in android mediplayer? I used the below code. seekbar working at a firstsong only then turn away from my application.
mp = MediaPlayer.create(player.this, (Integer) plsong.get(i));
mp.start();
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
mp.release();
sname.setText(" ");
if (j < (plsong.size() - 1)) {
j++;
mp = MediaPlayer.create(player.this,(Integer) plsong.get(j));
sname.setText((CharSequence) soname.get(j));
mp.start();
mp.setOnCompletionListener(this);
}
}
});
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mpss) {
// TODO Auto-generated method stub
total = mp.getDuration();
System.out.println("total" + total);
}
});
seekbar.setProgress(0);
seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp.seekTo(progress);
seekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(MyCounter.this);
currentThread.start();
mplay = (Button) findViewById(R.id.mplay);
if(!mp.isPlaying())
{
mplay.setText("Pause");
mplay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mp.start();
seekbar.setMax(total);
}
});
}
else
{
mplay.setText("play");
mplay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mp.pause();
}
});
}
}
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
seekbar.setProgress(msg.what);
}
};
Remove all the threads you created to move the seekbar and add these:
mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener(){
public void onBufferingUpdate(MediaPlayer mp, int percent) {
SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar);
if (mp.isPlaying() && seekBar!=null) {
seekBar.setProgress(mp.getCurrentPosition());
}
}
});

Android seekbar with streaming audio

I currently have a media player that is streaming a mp3. I have a seekbar, hwoever, it is not working. I have tried it with an actual raw file and that seems to work. I think the seekbar is not getting the duration of the song. any ideas?
Code:
public class SeekMe extends Activity implements Runnable{
/** Called when the activity is first created. */
MediaPlayer mp;
Button playButton;
Button stopButton;
SeekBar seekMe;
int total;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
playButton = (Button)findViewById(R.id.play);
stopButton = (Button)findViewById(R.id.stop);
seekMe = (SeekBar)findViewById(R.id.seekBar1);
final MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource("http://dl.dropbox.com/u/24535120/Week%20of%20May%201/Swanky%20Tunes%20%26%20Hard%20Rock%20Sofa%20-%20Smolengrad%20%28Original%20Mix%29.mp3");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.prepareAsync();
} 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();
}
mp.setOnPreparedListener(new OnPreparedListener(){
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
total = mp.getDuration();
}
});
seekMe.setProgress(0);
playButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
mp.start();
seekMe.setMax(total);
}
});
stopButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
mp.pause();
}
});
seekMe.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser){
mp.seekTo(progress);
seekMe.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
while(mp != null){
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
}catch (InterruptedException e){
e.printStackTrace();
}
}
private Handler threadHandler = new Handler(){
public void handleMessage(Message msg){
seekMe.setProgress(msg.what);
}
};
}
Have you tried calling the default music player with the url of the mp3 file?
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse(url), "audio/*");
context.startActivity(i);

Categories

Resources