Seekbar not working - android

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) {
}
}

Related

How to use seekbar on a streaming media player?

I am working on an online radio app and I tried implementing a seek bar to it like the tunein. I gave the seekbar a max value since i could not use the MediaPlayer's .getDuration() method.
I successfully implemented it but when I try moving the seekbar it goes back to its previous position and somehow my play/pause button stops working.
HERE IS THE SUMMARISED CODE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
handler = new Handler(); //for seekbar
seekBar = (SeekBar) findViewById(R.id.seekBar);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
new PlayerTask().execute(radioLink);
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
started = false;
mediaPlayer.pause();
playButton.setImageResource(R.drawable.pplay);
} else {
started = true;
mediaPlayer.start();
playButton.setImageResource(R.drawable.ppause);
}
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(b)
{
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
class PlayerTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
loadingSoundtxt.setVisibility(View.GONE);
playButton.setVisibility(View.VISIBLE);
seekBar.setMax(1800000); //30mins in milliseconds
mediaPlayer.start();
changeSeekbar();
}
}
private void changeSeekbar(){
seekBar.setProgress(mediaPlayer.getCurrentPosition());
if (mediaPlayer.isPlaying())
{
runnable = new Runnable() {
#Override
public void run() {
changeSeekbar();
}
};
handler.postDelayed(runnable, 1000);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) mediaPlayer.release();
}
}

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

Music stops when playing in background.I don't want to use it as a service..what are my alternatives?

i am developing a music player app and it plays the music fine,but the problem comes when it is playing in the background,it stops after some time....i have searched it on the net to how to resolve this problem,almost all of them were using a service instead of activity and i don't want to do that,so how can i achieve that??
here is the code i am using
public class NowPlaying extends Activity implements Serializable {
static MediaPlayer mp =new MediaPlayer();
/*SeekBar songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
TextView songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
TextView songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
private Handler mHandler = new Handler();
private Utilities utils;
*/
#SuppressLint("NewApi")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.now_playing);
Intent i = getIntent();
final int position=i.getIntExtra("Data2", 0);
final ArrayList<SongDetails> songs = getIntent().getParcelableArrayListExtra("Data1");
SongDetails songDetails = songs.get(position) ;
Button bfake=(Button) findViewById(R.id.bFake);
LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
Button Pause=(Button)findViewById(R.id.bPlayPause);
Playservice(songs,position,0 );
bfake.setOnTouchListener(new OnSwipeTouchListener()
{ int z=0;
public void onSwipeRight() {
z=z-1;
Playservice(songs,position,z );
}
public void onSwipeLeft() {
z=z+1;
Playservice(songs,position,z );
}
public void onSwipeBottom() {
mp.stop();
}
});
LL.setOnTouchListener(new OnSwipeTouchListener() {
public void onSwipeBottom() {
mp.stop();
}
});
Pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{if(mp.isPlaying())
mp.pause();
else
mp.start();
}
});
}
private void Playservice( ArrayList<SongDetails> songs, int position, int i )
{
/* Utilities utils = new Utilities();
songProgressBar.setOnSeekBarChangeListener((OnSeekBarChangeListener) this); // Important
*///mp.setOnCompletionListener((OnCompletionListener) this);
try {
String ab=songs.get(position+i).getPath2().toString();
if(mp.isPlaying())
{ mp.stop();
}
mp.reset();
mp.setDataSource(ab) ;
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You have to use a foreground Service for this. The probability that a background Activity or a background Service gets killed by Android is very high. This is the problem you observe.
I faced the same problem and what I did was to set the service on foreground in service OnCreate method
startForeground(R.string.app_name, aNotification);

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

Categories

Resources