get the current state of MediaPlayer in Android - android

I am not much experienced so I copied code from somewhere; but Now I can get the state mediaplayer; All I want to do is to get the current state of mediaplayer and then show pause button when it's playing ; and play button when it's paused/buffering;
I am using shoutcast streaming in it; I want to show pause button or something loading status when it is being loaded initially (buffering); and when it is loaded and started playing the the pause button ; and when for some reason it starts buffering again it should show play button or Loading status on main activity
here is my code;
public class Myradio extends AsyncTask implements OnBufferingUpdateListener {
private static Context mContext;
// private static MyProgressDialog pdialog;
public static MediaPlayer mp = new MediaPlayer();
private MediaPlayer mpLoop = new MediaPlayer();
public Myradio(Context theContext) {
mContext = theContext;
mp.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer arg0, int arg1) {
Log.v("Buffring Update", "");
// TODO Auto-generated method stub
}
});
}
public static void startRadio(String streamUrl) {
mp.reset();
mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what
+ ") with extra (" + extra + ")");
return false;
}
});
try {
mp.setDataSource(streamUrl);
mp.prepare();
mp.start();
} catch (IllegalArgumentException e) {
} catch (IllegalStateException e) {
} catch (IOException e) {
}
}
public static void stopRadio() {
mp.stop();
}
public static void resumeRadio() {
// mp.();
// mp.setLooping(false);
// mpLoop.stop();
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
// TODO Auto-generated method stub
Log.v("Buffring Update", "Buffring Update");
}
}

You can do this like (see here):
if(MediaPlayer.isPlaying()){
//show the pause button
}
else{
//show the play button
}
Check this tut too.

Related

Audio Playing from URI Inside Listview , But Seekbar is not Updating in Android Listview item

I am Playing a Audio from Uri Its Working Fine.
Clicking a Button from Each Listview item.
Problem :Audio is Playing in the Listview ,but still Seekbar is not Moving(Updating).
EDIT:1
1.Audio is Playing in the Each Listview Item Perfectly,But Seekbar is Not Working(Not Updating).
Please Help me top solve this Issue.
My Listview Array adapter Class:
Adapter.class
private static final int UPDATE_FREQUENCY = 500;
int progress=0;
public View getView(final int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.audio_listview, null, true);
ListenAUdioButton = (Button) rowView.findViewById(R.id.ListenAudiobuttonxml);
seek_bar_view = (SeekBar) rowView.findViewById(R.id.seek_bar);
ListenAUdioButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// text_shown.setText("Playing...");
try {
try {
// get Internet status
isInternetPresent = cd1.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
if (!itemname3_AUDIO_FILE[position].equals("") || !itemname3_AUDIO_FILE[position].equals("null")) {
System.out.println(" AUDIO FILE :-)" + itemname3_AUDIO_FILE[position]);
player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(context, Uri.parse(itemname3_AUDIO_FILE[position]));
player.prepareAsync();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
try {
mp.start();
seek_bar_view.setMax(player.getDuration());
updatePosition();
} catch (Exception e) {
e.printStackTrace();
}
}
});
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
});
MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// returning false will call the OnCompletionListener
return false;
}
};
} else {
Toast.makeText(getContext(), "Audio Not Found..!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "Please Check Your Internet Connection..!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "Audio Not Found..!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
return rowView;
}
private void stopPlay() {
player.stop();
player.reset();
// playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seek_bar_view.setProgress(0);
// isStarted = false;
}
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
private void updatePosition()
{
handler.removeCallbacks(updatePositionRunnable);
seek_bar_view.setProgress(progress);
progress=getProgressPercentage(player.getCurrentPosition(),player.getDuration();
notifyDataSetChanged();
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
you need to update your seekbar position(value) at every second..
To set seekbar Max value..
seek_bar_view.setMax((int) player.getDuration());
and update it every second to show progress
Handler mHandler = new Handler();
runOnUiThread(new Runnable() {
#Override
public void run() {
seek_bar_view.setProgress((int) player.getCurrentPosition());
}
mHandler.postDelayed(this,1000);
}
);
See this:
seek_bar_view.setProgress(player.getCurrentPosition());
here player.getCurrentPosition() returns the time in millis , you need to convert this to int and then set the progress to seekBar.
Try this:
public static int getProgressPercentage(long currentDuration, long totalDuration){
Double percentage = (double) 0;
long currentSeconds = (int) (currentDuration / 1000);
long totalSeconds = (int) (totalDuration / 1000);
// calculating percentage
percentage =(((double)currentSeconds)/totalSeconds)*100;
// return percentage
return percentage.intValue();
}
and now get the percentage for your SeekBar like this:
int currentProgress=getProgressPercentage(player.getCurrentPosition(), player.getDuration());
seek_bar_view.setProgress(currentProgress);
Edited:
For your specific case, inside a ListView item:
You will need to notify the adapter each time you change the position of seekbar.
For this, the simplest approach would be to take a variable inside the POJO class you are using to set the adapter.
Inside your POJO class
int progress=0;
In your adapter,set the seekbar progress
seekbar.setProgress(progress);
In your adapter,change the value of progress and notifyadapter
progress=getProgressPercentage(player.getCurrentPosition(), player.getDuration());
notifyDataSetChanged()
//Re-Edited:
seekBar.setOnSeekBarChangeListener(new 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
notifyDataSetChanged();
}
});

Audio Streaming Seekbar Hides while song is playing

I can't find a way to stop hiding the seekbar. As soon as the song plays the seekbar hides after 2-3 sec. I am really new into this so not really sure how I can approach to this issue. I tried putting mediaController.show() into my methods when the song is playing but no luck. I found this code from a Youtube Channel below is the code:
public class MainActivity extends ListActivity implements OnPreparedListener,
MediaController.MediaPlayerControl {
private static final String TAG = "AudioPlayer";
private ListView list;
private MainArrayAdapter adapter;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private String audioFile;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = getListView();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
ArrayList<String> array_list_music = new ArrayList<String>();
array_list_music.add("Sammy Kaye And His Orchestra" + " ### "
+ "Minka (1941)" + " ### "
+ "http://incoming.jazz-on-line.com/a/mp3w/1941_149.mp3");
adapter = new MainArrayAdapter(MainActivity.this, array_list_music);
setListAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Object item = getListView().getItemAtPosition(arg2);
String the_list_item = item.toString();
Toast.makeText(MainActivity.this,
"You clicked " + the_list_item, Toast.LENGTH_LONG)
.show();
String[] aux = the_list_item.split(" ### ");
String url_to_play = aux[2];
playAudio(url_to_play);
}
});
}
private void playAudio(String url_to_play) {
//----- stop & reset
try {
mediaPlayer.stop();
mediaPlayer.reset();
} catch (Exception e) {
// TODO: handle exception
}
try {
mediaPlayer.setDataSource(url_to_play);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e(TAG, "Could not open file " + url_to_play + " for playback.",
e);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mediaController.show();
return true;
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public void seekTo(int arg0) {
mediaPlayer.seekTo(arg0);
}
#Override
public void start() {
mediaPlayer.start();
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(list);
mediaController.show();
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
}

How to make a radio app keep playing in the background of my Android App

Am still new to android, but i followed a tutorial online in developing a radio Application, now this is the problem am encountering, i want this radio to keep playing, so that the app user can keep using the app or other application while the radio plays in the background. The radio stops playing when the user leave the streaming page.
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
player.start();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(" radio URL");
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
player.prepareAsync();
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(true);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.pause();
buttonStopPlay.setEnabled(false);
buttonPlay.setEnabled(true);
}
}
refer this link
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}

State change listener for MediaPlayer

In this diagram are lot of states:
but with standard listener I can listen just some basic states.
So is possible to listen every states changes for MediaPlayer?
Unfortunately I found no way of doing this other than surrounding the MediaPlayer with a custom state machine container.
Added ...
You could create a container that is a singleton and defines it's own states. And the only interaction with the MediaPlayer is done through this container. All other classes need to access the API of the container.
Below is a simple outline:
public class MyContainer implements OnBufferingUpdateListener,
OnCompletionListener,
OnErrorListener,
OnInfoListener,
OnPreparedListener
{
static enum MP_STATES
{
MPS_IDLE,
MPS_INITIALIZED,
MPS_PREPARING,
MPS_PREPARED,
MPS_STARTED,
MPS_STOPPED,
MPS_PAUSED,
MPS_PLAYBACK_COMPLETED,
MPS_ERROR,
MPS_END,
}
private static MyContainer s_mpm = null;
private MP_STATES m_eState;
private MediaPlayer m_mp;
public static MyContainer get()
{
if (null == s_mpm)
{
s_mpm = new MyContainer();
}
return s_mpm;
}
private MyContainer()
{
m_mp = new MediaPlayer();
m_mp.setOnBufferingUpdateListener(this);
m_mp.setOnCompletionListener(this);
m_mp.setOnErrorListener(this);
m_mp.setOnInfoListener(this);
m_mp.setOnPreparedListener(this);
m_eState = MP_STATES.MPS_IDLE;
}
public MP_STATES getState()
{
return m_eState;
}
public void setUrl(String szUrl)
{
bringToIdleState();
try {
m_mp.setDataSource(szUrl);
m_eState = MP_STATES.MPS_INITIALIZED;
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
m_mp.prepareAsync();
m_eState = MP_STATES.MPS_PREPARING;
}
public void play()
{
switch (m_eState)
{
case MPS_PREPARED:
case MPS_PAUSED:
m_mp.start();
m_eState = MP_STATES.MPS_STARTED;
break;
default:
// !! throw exception
}
}
public void pause()
{
switch (m_eState)
{
case MPS_STARTED:
m_mp.pause();
m_eState = MP_STATES.MPS_PAUSED;
break;
default:
// !! throw exception
}
}
public void release()
{
m_mp.release();
m_mp = null;
}
private void bringToIdleState()
{
// reset() should bring MP to IDLE
m_mp.reset();
m_eState = MP_STATES.MPS_IDLE;
}
// ** Callbacks
#Override
public void onPrepared(MediaPlayer mp)
{
m_eState = MP_STATES.MPS_PREPARED;
m_mp.start();
m_eState = MP_STATES.MPS_STARTED;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra)
{
return false;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
m_eState = MP_STATES.MPS_IDLE;
return false;
}
#Override
public void onCompletion(MediaPlayer mp)
{
// play the next song
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
}
}
}

setLooping don't work in my videoplayer

I am a Android newbie. I want to design my personal videoplayer to play streaming music, so I use MediaPlayer and SurfaceView. The project plays streaming video successfully, but it can't be setloop. I have google many articles and read Android Developer. I can't figure out why mediaPlayer.setLooping(true) don't work here. Thanks^^
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
The code includes two parts: 1.Test_Videoplayer.java 2.Player.java
1.Test_Videoplayer.java
public class Test_Videoplayer extends Activity {
private SurfaceView surfaceView;
private Button btnPause, btnPlayUrl, btnStop;
private SeekBar skbProgress;
private Player player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) this.findViewById(R.id.surfaceView1);
btnPlayUrl = (Button) this.findViewById(R.id.btnPlayUrl);
btnPlayUrl.setOnClickListener(new ClickEvent());
btnPause = (Button) this.findViewById(R.id.btnPause);
btnPause.setOnClickListener(new ClickEvent());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ClickEvent());
skbProgress = (SeekBar) this.findViewById(R.id.skbProgress);
skbProgress.setOnSeekBarChangeListener(new SeekBarChangeEvent());
player = new Player(surfaceView, skbProgress);
}
class ClickEvent implements OnClickListener {
#Override
public void onClick(View arg0) {
if (arg0 == btnPause) {
player.pause();
} else if (arg0 == btnPlayUrl) {
String url = "http://sites.google.com/site/ronforwork/Home/android-2/littleMonster.3gp";
player.playUrl(url);
} else if (arg0 == btnStop) {
player.stop();
}
}
}
class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
int progress;
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
this.progress = progress * player.mediaPlayer.getDuration()
/ seekBar.getMax();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.mediaPlayer.seekTo(progress);
}
}
}
2.Player.java <-- here is mediaPlayer.setLooping(true)
public class Player implements OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private int videoWidth;
private int videoHeight;
public MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SeekBar skbProgress;
private Timer mTimer = new Timer();
public Player(SurfaceView surfaceView, SeekBar skbProgress) {
this.skbProgress = skbProgress;
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mTimer.schedule(mTimerTask, 0, 1000);
}
TimerTask mTimerTask = new TimerTask() {
#Override
public void run() {
if (mediaPlayer == null)
return;
if (mediaPlayer.isPlaying() && skbProgress.isPressed() == false) {
handleProgress.sendEmptyMessage(0);
}
}
};
Handler handleProgress = new Handler() {
public void handleMessage(Message msg) {
int position = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if (duration > 0) {
long pos = skbProgress.getMax() * position / duration;
skbProgress.setProgress((int) pos);
}
};
};
public void play() {
mediaPlayer.start();
}
public void playUrl(String videoUrl) {
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(videoUrl);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
} 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();
}
}
public void pause() {
mediaPlayer.pause();
}
public void stop() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.e("mediaPlayer", "surface changed");
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnPreparedListener(this);
} catch (Exception e) {
Log.e("mediaPlayer", "error", e);
}
Log.e("mediaPlayer", "surface created");
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("mediaPlayer", "surface destroyed");
}
#Override
public void onPrepared(MediaPlayer arg0) {
videoWidth = mediaPlayer.getVideoWidth();
videoHeight = mediaPlayer.getVideoHeight();
if (videoHeight != 0 && videoWidth != 0) {
arg0.start();
}
Log.e("mediaPlayer", "onPrepared");
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
public void onBufferingUpdate(MediaPlayer arg0, int bufferingProgress) {
skbProgress.setSecondaryProgress(bufferingProgress);
int currentProgress = skbProgress.getMax()
* mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration();
Log.e(currentProgress + "% play", bufferingProgress + "% buffer");
}
}

Categories

Resources