I'm trying to create something where a single audio file is played and can be paused and manipulated with a progress/seek bar. I want to have an image taking up most of the screen and then a play pause button on the bottom left and the bar to the right of the button. Everything works the seekbar which isn't link to the audio. My progress bar coding is a probably a mess because if taken it from several i've seen on the internet but they are mostly confusing for me as they are for music player apps not for playing a single audio file.
Could someone please help me with the progress bar? Any other tips on improving my programming would be great too.
(I am very new to android and programming just to warn you)
This is my Java:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
int total;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekListener);
initMediaPlayer();
Thread currentThread = new Thread(this);
currentThread.start();
}
private void initMediaPlayer() {
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
total = mediaPlayer.getDuration();
}
});
seekBar.setProgress(0);
seekBar.setMax(total);
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekListener = 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) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mediaPlayer != null) {
int currentPosition = mediaPlayer.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);
}
};
And this is what my java was before i tried to use the seekBar:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
initMediaPlayer();
}
private void initMediaPlayer() {
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
}
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
This is my java after Vishal Vaja's answer:
MediaPlayer mediaPlayer;
Button buttonPlayPause;
ImageView Image;
SeekBar seekBar;
Handler handler;
private int stateMediaPlayer;
private final int stateMP_NotStarter = 0;
private final int stateMP_Playing = 1;
private final int stateMP_Pausing = 2;
private int mediaPos;
private int mediaMax;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playerwere);
Image = (ImageView) findViewById(R.id.pdfview);
Image.setImageResource(R.drawable.wereim);
seekBar = (SeekBar) findViewById(R.id.seekBar);
buttonPlayPause = (Button) findViewById(R.id.playpause);
buttonPlayPause.setOnClickListener(buttonPlayPauseOnClickListener);
seekBar.setOnSeekBarChangeListener(seekBarOnSeekChangeListener);
initMediaPlayer();
}
private void initMediaPlayer() {
handler = new Handler();
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(were.this, R.raw.were);
stateMediaPlayer = stateMP_NotStarter;
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
// seekBar.setProgress(mediaPos);// set
// current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); // Looping the thread after 0.1
// second
// seconds
}
}
};
Button.OnClickListener buttonPlayPauseOnClickListener = new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (stateMediaPlayer) {
case stateMP_NotStarter:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
case stateMP_Playing:
mediaPlayer.pause();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_play);
stateMediaPlayer = stateMP_Pausing;
break;
case stateMP_Pausing:
mediaPlayer.start();
buttonPlayPause
.setBackgroundResource(android.R.drawable.ic_media_pause);
stateMediaPlayer = stateMP_Playing;
break;
}
}
};
SeekBar.OnSeekBarChangeListener seekBarOnSeekChangeListener = 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) {
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
};
I think this can be work for you.
Create one thread that will check song position and will move seekbar like this,
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if(mediaPlayer.isplaying){
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekBar.setMax(mediaMax_new);
seekBar.setProgress(mediaPos_new);
handler.postDelayed(this, 100); //Looping the thread after 0.1 second
// seconds
}
}
};
And call that thread like this,
mediaPos = mediaPlayer.getCurrentPosition();
mediaMax = mediaPlayer.getDuration();
seekBar.setMax(mediaMax); // Set the Maximum range of the
seekBar.setProgress(mediaPos);// set current progress to song's
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
public class DetailMusic extends Activity implements View.OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
TextView text_shown;
Handler seekHandler = new Handler();
Bundle bundle = new Bundle();
String Musicnames;
int mediaMax;
int mediaPos = 0;
MediaPlayer mp = new MediaPlayer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailmusic);
bundle = getIntent().getExtras();
if (bundle != null) {
Musicnames = bundle.getString("musicnbames");
System.out.println("++++++++++++++++++++++++++++++++" + Musicnames);
Log.e("musicfoldername", Musicnames);
}
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);
//seekUpdation();
String PATH_TO_FILE = Musicnames;
// MediaPlayer mp = new MediaPlayer();
try {
mp.setDataSource(PATH_TO_FILE);
mp.prepare();
} catch (IOException e) {
}
mp.start();
seek_bar.setMax(mp.getDuration());
try {
mp.setDataSource(Musicnames);
} 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();
}
mediaPos = mp.getCurrentPosition();
mediaMax = mp.getDuration();
seek_bar.setMax(mediaMax); // Set the Maximum range of the
seek_bar.setProgress(mediaPos);// set current progress to song's
seekHandler.removeCallbacks(moveSeekBarThread);
seekHandler.postDelayed(moveSeekBarThread, 100); //cal the thread after 100 milliseconds
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mp.isPlaying()) {
int mediaPos_new = mp.getCurrentPosition();
int mediaMax_new = mp.getDuration();
seek_bar.setMax(mediaMax_new);
seek_bar.setProgress(mediaPos_new);
seekHandler.postDelayed(this, 100); //Looping the thread after 0.1 second
}
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
mp.reset();
// mp.start();
text_shown.setText("Playing...");
break;
case R.id.pause_button:
mp.pause();
text_shown.setText("Paused...");
}
}
}
Related
I have the problem with the seekbar thumb, although I have added every necessary codes for it to work. still the seekbar thumb doesn't play from the point dragged by the user. instead the thumb positioned itself back to the point it was last playing though. Any help will be appreciated.
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton4);
player = MediaPlayer.create(this, R.raw.songnames);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton3);
seekbar = (SeekBar) findViewById(R.id.mantraProgressBar);
seekbar.setVisibility(ProgressBar.VISIBLE);
seekbar.setProgress(0);
seekbar.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
im.setImageResource(R.drawable.pause_tran);
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu - 5000);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int cu = player.getCurrentPosition();
player.seekTo(cu + 5000);
}
});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton3) {
if (player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.play_tran);
} else {
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1 = (ImageButton) this.findViewById(R.id.imageButton3);
img1.setImageResource(R.drawable.pause_tran);
}
}
}
#Override
public void run() {
int currentPosition = 0;
String s;
int total = player.getDuration();
while (player != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekbar.setProgress(currentPosition);
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
player.seekTo(progress);
seekbar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
public class MainActivity extends AppCompatActivity {
private MyVideoView mVV;
private Handler mhandler;
private SeekBar seekbar;
private int duration;
private int backPositon = 0;
private int currentPosition;
private SharedPreferences sp;
private MediaController controller;
private TextView tv_curr;
private TextView tv_duration;
private Handler handler;
private boolean mExit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mVV = (MyVideoView) findViewById(R.id.vv);
seekbar = (SeekBar) findViewById(R.id.seekbar);
tv_curr = (TextView) findViewById(R.id.tv_currtime);
tv_duration = (TextView) findViewById(R.id.tv_duration);
//get duration of video
getDuration();
//video start
playVideo();
//get current time
getCurrentDuration();
//listener
initEvent();
}
private void initHanlder() {
handler=new Handler(){
#Override
public void handleMessage(Message msg) {
if (msg.what==0x123){
tv_curr.setText(timeFormat(mVV.getCurrentPosition()));
seekbar.setProgress(mVV.getCurrentPosition());
}
if(msg.what==0x133){
int changedProgress = msg.arg1;
tv_curr.setText(timeFormat(changedProgress));
mVV.seekTo(changedProgress);
seekbar.setProgress(changedProgress);
mVV.start();
}
}
};
new Thread(new Runnable() {
#Override
public void run() {
while (mVV.getCurrentPosition()<duration){
Message message = Message.obtain();
message.what=0x123;
handler.sendMessage(message);
SystemClock.sleep(1000);
if(mExit){
break;
}
}
}
}).start();
}
private void getDuration() {
mVV.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
duration = mVV.getDuration();
timeFormat(duration);
Log.d("TAG", "---duration" + timeFormat(duration));
seekbar.setMax(duration);
//TextView time
tv_duration.setText(timeFormat(duration));
//init handler
initHanlder();
}
});
}
private String timeFormat(int time) {
StringBuilder mFormatBuilder;
Formatter mFormatter;
mFormatBuilder = new StringBuilder();
mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());
int totalSeconds = time / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
mFormatBuilder.setLength(0);
if (hours > 0) {
return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return mFormatter.format("%02d:%02d", minutes, seconds).toString();
}
}
private void playVideo() {
File file = new File(Environment.getExternalStorageDirectory(), "cgx_video/db.mp4");
if (!file.exists()) {
file.mkdir();
}
Log.d("TAG", file.toString());
mVV.setVideoPath(file.getPath());
mVV.start();
}
private void initEvent() {
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
currentPosition=progress;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mVV.pause();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(handler!=null){
Message message = Message.obtain();
message.what=0x133;
message.arg1=currentPosition;
handler.sendMessage(message);
}
}
});
}
#Override
protected void onPause() {
super.onPause();
Log.d("TAG", "---onPause");
mVV.pause();
backPositon = mVV.getCurrentPosition();
Log.d("TAG", "backPositon:" + backPositon);
}
#Override
protected void onStop() {
super.onStop();
Log.d("TAG", "---onStop");
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", backPositon + "---backPositon");
mVV.seekTo(backPositon);
mVV.start();
}
#Override
protected void onDestroy() {
//in case of leak of memeroy
mExit=true;
super.onDestroy();
}
}
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();
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();
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().
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);