Implementing SeekBar in Android in BaseAdapter - android

In my application I am trying to implement SeekBar.. The SeekBar is working fine when playing the sound at first time. but When I click the button to play the sound again then I am an endless loop of errors regarding the MediaPlayer. The thing that I want is that when I while playing the sound if I click the the play button the sound should play again from the beginning and the SeekBar should also start from beginning. If I remove the the SeekBar then everything is working fine.. But SeekBar is must in my application.. I have implemented all these things in the BaseAdapter.. I have to do all the things in the BaseAdapter. So please help me in letting me the code that works with the BaseAdapter..
This is my code... Please have a look...
mediaPlayer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Loading Message", Toast.LENGTH_LONG).show();
mp.reset();
try {
mp.setDataSource("url for any mp3 audio file");
} 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.prepareAsync();
mp.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(final MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
mediaPlayer.setBackgroundResource(R.drawable.m_pause);
seekBar.setProgress(0);
seekBar.setMax(100);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
});
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mediaPlayer.setBackgroundResource(R.drawable.m_play);
mp.stop();
try {
mUpdateTimeTask.join();
mHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.removeCallbacks(mUpdateTimeTask);
}
});
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(final SeekBar seekBar) {
// TODO Auto-generated method stub
//mHandler.removeCallbacks(mUpdateTimeTask);
if(mp.isPlaying())
{
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
mp.seekTo(currentPosition);
mUpdateTimeTask = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long totalDuration = mp.getDuration();
long currentDuration = mp.getCurrentPosition();
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
//timer.setText(""+utils.milliSecondsToTimer(currentDuration));
seekBar.setProgress(progress);
mHandler.post(this);
}
});
mUpdateTimeTask.start();
}
else
{
seekBar.setProgress(0);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
if(mp.isPlaying())
{
mHandler.removeCallbacks(mUpdateTimeTask);
}
else
{
seekBar.setProgress(0);
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mp.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
});
Thanks...

Create a method in your BaseAdapter which sets the current seekbarprogress to zero
void setSeekBarValuetoZero(){
seekBar.setProgress(0);
}
Please check the initially that seekbar is initialized.
You can call this function from yourMediaPlayer class before mp.reset();

Related

how to stream a online radio without any stuck over streaming?

how to stream a online radio without any buffering after the player is played. It should buffered for few sec for continue playing the radio,but it get stuck for few sec and playing.
my Aync task:
class Player extends AsyncTask {
private ProgressDialog progress;
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.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);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
public void mute1(View v){
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
mediaPlayer.setVolume(0,0);
media.setVolume(0,0);
seekbar.setClickable(false);
seekbar.setFocusable(false);
seekbar.setEnabled(false);
}
public void speaker1(View v){
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
mediaPlayer.setVolume(1,1);
media.setVolume(1,1);
seekbar.setClickable(true);
seekbar.setFocusable(true);
seekbar.setEnabled(true);
}
how to get my player prepare for the online radio without any streaming after player is started.
Please Help me..
my source is:
if (playPause) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = false;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute("http://streaming.shoutcast.com/MUKILFMRADIO");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
}
playPause = true;
}
};
I would suggest to use Exoplayer than media player.ExoPlayer is an application level media player for Android. It provides an alternative to Android’s MediaPlayer API for playing audio and video both locally and over the Internet. ExoPlayer supports features not currently supported by Android’s MediaPlayer API, including DASH and SmoothStreaming adaptive playbacks. Unlike the MediaPlayer API, ExoPlayer is easy to customize and extend, and can be updated through Play Store application updates. This links give you better idea about Exoplayer.
https://developer.android.com/guide/topics/media/exoplayer.html
https://github.com/google/ExoPlayer

How do I call mediaplayer once only?

In android, I have a mediaplayer on detail screen, which duplicates when I select another screen then play another detail, causing sound files to play on the same time. how do I fix this problem? Id like to play the most recent selected media only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feeddetail);
tc_recDurat = (TextView)findViewById(R.id.recDetDurat);
tc_recDuratBack = (TextView)findViewById(R.id.recDetDuratBack);
TextView tc_recPath = (TextView)findViewById(R.id.recDetPath);
recPath = (String) intent.getSerializableExtra("INTENT_PATH");
tc_recPath.setText(recPath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(recPath);
} catch (IOException e1) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), e1.getLocalizedMessage(), Toast.LENGTH_LONG);
}
ImageButton mClickButton1 = (ImageButton)findViewById(R.id.btnPlay);
mClickButton1.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer !=null){
try {
mediaPlayer
mediaPlayer.prepare();
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
seekUpdate();
isPlaying = true;
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
ImageButton mClickButton2 = (ImageButton)findViewById(R.id.btnStop);
mClickButton2.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mediaPlayer.stop();
isPlaying = false;
}
});
I am not sure what your problem is, but i believe you are trying to say that as you change through different activities, the sounds files do not stop playing
In that case you can do the following
In the activity
You can override the onPause method and put mediaPlayer.stop() inside it
#Override
public void onPause() {
super.onPause();
mediaPlayer.stop();
}

Playing music even after the UI has been closed

Well I am a bit confused with the following.
I have a class (Main Player UI) that has the mediaplayer object.
Now the problem is that I want the music to played even after the UI has been disposed, hence I have to depend on the service.
But then if I move the MediaPlayer to the Service class
How am I going to control the onCompletion(MediaPlayer arg0) when the player UI is shown up, which also needs to show the change in the song? But then the method has to be included in the Service method.
How do I make the Play buttons on the UI to start the song that is available in the Service method?
Please guide me. The current player class that holds the UI as well as the mediaplayer is as follows:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boombastic_player);
//INITIALIZATIONS
mMediaPlayer=new MediaPlayer();
utils = new Utilities();
songProgressBar=(SeekBar)findViewById(R.string.seeker);
play=(Button)findViewById(R.string.play);
next=(Button)findViewById(R.string.next);
previous=(Button)findViewById(R.string.previous);
playlist=(Button)findViewById(R.string.Playlist);
search=(Button)findViewById(R.string.search);
repeat=(Button)findViewById(R.string.repeat);
shuffle=(Button)findViewById(R.string.shuffle);
starttime=(TextView)findViewById(R.string.startTime);
endtime=(TextView)findViewById(R.string.endTime);
ObjectIntermediate=new Intermediate();
srvMplayer=new ServiceMan();
//Preparation
if(!Searched)
{
GetAllSongs();
Searched=true;
ShowToast("Finished Search");
}
songProgressBar.setOnSeekBarChangeListener(this); // Important
mMediaPlayer.setOnCompletionListener(this);
play.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check for already playing
if(mMediaPlayer.isPlaying())
{
if(mMediaPlayer!=null)
{
mMediaPlayer.pause();
/* Release Service*/
// Changing button image to play button
play.setBackgroundResource(R.drawable.playback_play);
}
}
else
{
// Resume song
if(mMediaPlayer!=null)
{
mMediaPlayer.start();
/* Starting Service*/
// Changing button image to pause button
play.setBackgroundResource(R.drawable.pause);
}
}
}
});
next.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check if next song is there or not
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(isShuffle)
{
ShuffleSong();
playSong(currentSongIndex);
}
else if(currentSongIndex < (BoombasticPlayer.Songslist.size() - 1))
{
try
{
ShowToast(Integer.toString(currentSongIndex));
playSong(currentSongIndex + 1);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = currentSongIndex + 1;
}
else
{
// play first song
try
{
playSong(0);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = 0;
}
}
});
previous.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(currentSongIndex > 0)
{
try {
playSong(currentSongIndex - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = currentSongIndex - 1;
}
else
{
// play last song
try {
playSong(BoombasticPlayer.Songslist.size() - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = BoombasticPlayer.Songslist.size() - 1;
}
}
});
playlist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent playlistIntent= new Intent(arg0.getContext(), Playlist.class);
startActivityForResult(playlistIntent, MODE_APPEND);
}
});
repeat.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat==true)
{
isRepeat=false;
ShowToast("Repeat OFF");
}
else
{
isRepeat=true;
ShowToast("Repeat ON");
}
}
});
shuffle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isShuffle==true)
{
isShuffle=false;
ShowToast("Shuffle OFF");
}
else
{
isShuffle=true;
ShowToast("Shuffle ON");
}
}
});
}

MediaPlayer play next track from /res/raw

I'm making an lullaby app.Initially there are two tracks in my /res/raw folder.
On completing first track I want it to play next track.
i did this using onCompletionListener.But it is showing force close error.
Below is my code for that.
So can anyone tell me how to do that?
public class PlayRandom extends Activity implements OnCompletionListener{
MediaPlayer mp;
int rnum;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playrandom);
mp.setOnCompletionListener(this);
mp = MediaPlayer.create(this, R.raw.lullaby1);
mp.start();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
mp.stop();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
File pdfFile = new File("res/raw/lullaby2.mp3");
Uri path = Uri.fromFile(pdfFile);
mp.stop();
try{
mp.setDataSource(getApplicationContext(), path);
mp.prepare();
mp.start();
} 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();
}
}
}
I tried this but still its not working.
That meand there's something wrong in OnClickListener.
public class PlayRandom extends Activity implements OnCompletionListener{
MediaPlayer mp;
int rnum;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playrandom);
mp.setOnCompletionListener(this);
mp = MediaPlayer.create(this, R.raw.lullaby1);
mp.start();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
mp.stop();
}
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Toast.makeText(this,"Yuppieee!!", Toast.LENGTH_SHORT);
}
}
use AssetFileDescriptor for playing file from raw folder:
AssetFileDescriptor afdes = getAssets().openRawResourceFd(R.raw.lullaby2);
mp.reset();
mp.setDataSource(afdes.getFileDescriptor(), afdes.getStartOffset(), afdes.getLength());
mp.prepare();
mp.start();

Seekbar Doesnt move while playing

I have recorded audio, and play it through the mediaplayer. Recording, playing works fine. I used a seekbar, while playing the recorded voice. I used the following coding to play the content stored in sdcard. It works fine.. mFileName is the audio file in sdcard.
The seek bar doesnt move, while playing. Any suggestions...
private void startPlaying()
{
MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFileName);
mPlayer.prepare();
mPlayer.start();
mSeekBar.setMax(mPlayer.getDuration());
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
And I used
mSeekBar.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){
mPlayer.seekTo(progress);
mSeekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread((Runnable) this);
currentThread.start();
public void run() {
// TODO Auto-generated method stub
try {
while(mPlayer != null){
int currentPosition = mPlayer.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler threadHandler = new Handler(){
public void handleMessage(Message msg){
mSeekBar.setProgress(msg.what);
}
};
The progressbar moves only when the user moves. It doent move atomatically.
The seekbar isn't going to magically update itself to show the MediaPlayer's current position. Here's a link that shows how to do this with a polling thread that checks the MediaPlayer's position every second or so and updates the seekbar accordingly:
http://united-coders.com/nico-heid/an-android-seekbar-for-your-mediaplayer

Categories

Resources