Android mediaplayer with seekbar - android

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

Related

Seekbar for mp3 from sd card

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

android, song controller and seek bar in media player

in my music player how I can let my seek bar back to the starting point after I clicked stop button? and set the text field of total duration and current position to zero ?? the problem happen when I click stop and then click play button ?in my log cat the error is "Attempt to call getDuration without a valid mediaplayer"
#Override
protected void onCreate(Bundle savedInstanceState) {
setVolumeControlStream(AudioManager.STREAM_MUSIC);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton play_btn= (ImageButton) findViewById(R.id.iv_play);
ImageButton backward_btn=(ImageButton)findViewById(R.id.imageView_backward);
ImageButton forward_btn= (ImageButton) findViewById(R.id.imageView_forward);
ImageButton stop_btn= (ImageButton) findViewById(R.id.imageView_stop);
ImageButton pause_btn= (ImageButton)findViewById(R.id.imageView_pause);
ImageButton shuffle_btn = (ImageButton) findViewById(R.id.imageView_shuffle);
song = MediaPlayer.create(getApplicationContext() ,R.raw.adele);
songProgressBar= (SeekBar) findViewById(R.id.seekBar1);
songProgressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = song.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
song.seekTo(currentPosition);
UpdateProgressBar();
}
#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
}
});
pause_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PauseSong(); }
private void PauseSong() {
// TODO Auto-generated method stub
song.pause();
}
});
stop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StopSong();
}
private void StopSong() {
// TODO Auto-generated method stub
song.stop();
}
});
play_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlaySong();
}
private void PlaySong() {
// TODO Auto-generated method stub
song.start();
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
UpdateProgressBar();
}
});
}
private void UpdateProgressBar() {
// TODO Auto-generated method stub
mHandler.postDelayed(mUpdateTimeTask, 100);
}
Runnable mUpdateTimeTask = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
totalDuration = song.getDuration();
currentDuration = song.getCurrentPosition();
// Displaying Total Duration time
songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);
songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);
songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));
// 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);
}
};
protected void onPause() {finish();}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Retrieve the duration from the onPrepared callback...this will ensure the music(audio) is properly loaded before you attempt to get it's duration.
song.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer song) {
int duration = song.getDuration();
song.start();
controller.show();
}
});
StopSong():
private void StopSong() {
if (song != null) {
song.stop();
song.release();
}
}
for the duration text field, i will used global variable to access from all functions.
#Override
protected void onCreate(Bundle savedInstanceState) {
int totalDuration 0;
.
.
.
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
mHandler.removeCallbacks(mUpdateTimeTask);
totalDuration = song.getDuration(); // here
.
.
.
private void StopSong() {
if (song!=null) {
song.stop();
song.release();
totalDuration = 0; // here
}
i hope this helps!

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

How to show seekbar along with the custom mediaplayer

i have build a custom media player and i want to show the seekbar also.
The seekbar is showing for now but is not functional i.e. it is not progressing when the song is played. Let me know where am i wrong . Following is the code
public class myPlayer extends Activity implements Runnable,SeekBar.OnSeekBarChangeListener {
MediaPlayer mPlayer;
Button play,stop;
SeekBar seekbar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
seekbar = (SeekBar)findViewById(R.id.seekbar);
mPlayer = MediaPlayer.create(this,R.raw.sajnave);
play=(Button)findViewById(R.id.play);
stop=(Button)findViewById(R.id.stop);
Toast.makeText(myPlayer.this, ""+mPlayer.getDuration(), Toast.LENGTH_SHORT).show();
play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mPlayer.start();
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(myPlayer.this, ""+mPlayer.getCurrentPosition(), Toast.LENGTH_SHORT).show();
mPlayer.stop();
}
});
}
#Override
public void run() {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekbar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
mPlayer.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Call updatePosition() method after mediplayer starts..It works for me.
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
if (player != null) seekbar.setProgress(player.getCurrentPosition());
handler.postDelaye(updatePositionRunnable, 500);
}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
player.seekTo(arg1);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
SurfaceView mPreview=(SurfaceView)findViewById(R.id.surface);
mPreview.postDelayed(runnable,200);
Runnable runnable = new Runnable() {
#Override
public void run() {
if (mMediaPlayer != null) {
if (isPlaying) {
// converting current position into seconds so dividing by
// 1000
try {
currentPosition = mMediaPlayer.getCurrentPosition();
mVideoProgress
.setProgress((int) ((currentPosition / (float) mMediaPlayer
.getDuration()) * 100f));
} catch (Exception e) {
e.printStackTrace();
}
mPreview.postDelayed(runnable, 150);
}
}
}
};

Categories

Resources