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)
{
}
}
}
Related
I have come along in leaps and bound with my first android app in the last three days. This is my last hurdle. How do I get my app to run a background Service that will allow the audio to keep playing? I have tried several examples I could find but they are based on playing a local (or streamed) mp3 file as opposed to a live (Icecast) mp3 stream.
Here's my code currently, everything works except background audio.
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageButton btn;
private ImageView img;
private boolean playPause;
private MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
//mp.start();
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!playPause) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
btn.setBackgroundResource(R.drawable.ic_rounded_pause_button);
img.setImageResource(R.drawable.ic_toweron);
img.setAlpha(1.0f);
playPause = true;
}
} else {
if(mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btn.setBackgroundResource(R.drawable.ic_play_button);
img.setImageResource(R.drawable.ic_toweroff);
img.setAlpha(0.3f);
playPause = false;
}
}
}
});
try {
mediaPlayer.setDataSource("http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p");
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Any help would be much appreciated.
use service to play audio file instant of activity.
here is simple code how to use media player in service.
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
//region "member variable"
boolean isServiceRunning = false;
ArrayList<Song> PlayerList = new ArrayList<>();
MediaPlayer mediaPlayer;
int position = 0;
MainActivity mainActivity;
private final IBinder mBinder = new LocalBinder();
int playingMood;
private final static int MAX_VOLUME = 15;
Toast toast;
public static MusicService objService;
//endregion
//region "service method"
#Override
public void onCreate() {
objService = this;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
isServiceRunning = true;
if (intent.getAction().equals(Constants.ACTION.STARTFOREGROUND_ACTION)) {
// showNotification(false);
} else if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
playPrevious();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
playNext();
} else if (intent.getAction().equals(
Constants.ACTION.STOPFOREGROUND_ACTION)) {
stop();
stopForeground(true);
stopSelf();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
isServiceRunning = false;
objService = null;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
//returns the instance of the service
public class LocalBinder extends Binder {
public MusicService getServiceInstance() {
return MusicService.this;
}
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
//endregion
//region "Media player"
public void SongRequest() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//Handel UI on main activity
mainActivity.showPlayer();
mediaPlayer = new MediaPlayer();
mainActivity.updatePlayerUI();
prepareMediaPlayer(PlayerList.get(position).getUrl());
} catch (Exception ex) {
ex.printStackTrace();
}
}
void showToast(String text) {
if (toast != null)
toast.cancel();
toast = Toast.makeText(App.getContext(), text, Toast.LENGTH_LONG);
toast.show();
}
#Override
public void onPrepared(MediaPlayer mp) {
// try {
mediaPlayer.start();
mainActivity.checkPlaying(true);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
try {
mainActivity.sentUpdateBroadcast(true);
if (playingMood == 1) {
mediaPlayer.start();
}
if (playingMood == 2) {
playNext();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (mainActivity != null)
mainActivity.updateProgressBuffer(percent);
if (percent == 1)
mainActivity.showPlayer();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
try {
Log.i("MediaPlayer", "error");
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
void startPrepare(String url) {
prepareMediaPlayer(url);
}
void prepareMediaPlayer(String url) {
try {
mediaPlayer.setDataSource(url);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(MusicService.this);
mediaPlayer.setOnErrorListener(MusicService.this);
mediaPlayer.setOnCompletionListener(MusicService.this);
mediaPlayer.setOnBufferingUpdateListener(MusicService.this);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
//endregion
//region "media player method"
public boolean play() {
if (mediaPlayer != null) {
switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
isServiceRunning = false;
if (mainActivity != null) {
mainActivity.ShowPlayer(0);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public void playNext() {
if (position < PlayerList.size() - 1) {
position++;
mediaPlayer.stop();
SongRequest();
}
}
public void playPrevious() {
if (position > 0) {
position--;
mediaPlayer.stop();
SongRequest();
}
}
public void onError() {
}
public void onCompletion() {
}
public void onCleanMemory() {
}
public void initilizePlayerList(ArrayList<Song> list, int position) {
this.PlayerList = list;
this.position = position;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
public boolean isRunning() {
return isServiceRunning;
}
public Song getCurrentSong() {
if (PlayerList != null && PlayerList.size() != 0 && PlayerList.size() >= position) {
return PlayerList.get(position);
}
return null;
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void seekTo(int duration) {
if (mediaPlayer != null) {
mediaPlayer.seekTo(duration);
}
}
public int getMood() {
return playingMood;
}
public void setMood(int mood) {
playingMood = mood;
}
public void setVolume(int soundVolume) {
if (mediaPlayer != null) {
final float volume = (float) (1 - (Math.log(MAX_VOLUME - soundVolume) / Math.log(MAX_VOLUME)));
mediaPlayer.setVolume(volume, volume);
}
}
//endregion
}
you can start your service from activity like this.
public void startMusicService() {
Intent serviceIntent = new Intent(MainActivity.this, MusicService.class);
serviceIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
for stop service use this code
public void stopMusicService() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
for bind service with activity use this
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
if (listHolder != null) {
initilizeSongsList(listHolder.list, listHolder.position);
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
where service is music service object in activity MusicService service;
So this is the working service for a single live stream URL thanks to asim.
public class StreamService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener {
public static final String ACTION_PLAY = "com.example.action.PLAY";
private static final String STREAM_URL = "...";
private static final String TEST_URL = "https://www.nasa.gov/mp3/586447main_JFKwechoosemoonspeech.mp3";
MainActivity mainActivity;
MediaPlayer mediaPlayer = null;
WifiManager.WifiLock wifiLock;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class LocalBinder extends Binder {
public StreamService getServiceInstance() {
return StreamService.this;
}
}
#Override
public void onCreate() {
super.onCreate();
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "mylock");
wifiLock.acquire();
try {
// Set the stream URL location
mediaPlayer.setDataSource(TEST_URL);
// prepareAsync must be called after setAudioStreamType and setOnPreparedListener
mediaPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
return false;
}
void switchButton() {
mainActivity.checkPlaying(!mediaPlayer.isPlaying());
}
public boolean play() {
if (mediaPlayer != null) {
//switchButton();
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
return false;
} else {
mediaPlayer.start();
return true;
}
}
return false;
}
public void stop() {
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
//player.start();
}
#Override
public void onDestroy() {
super.onDestroy();
if( wifiLock != null) wifiLock.release();
if (mediaPlayer != null) mediaPlayer.release();
}
public void registerClient(MainActivity activity) {
mainActivity = activity;
}
public boolean isplaying() {
return mediaPlayer == null ? false : mediaPlayer.isPlaying();
}
}
Which is implemented in the main activity:
public class MainActivity extends AppCompatActivity {
private ImageButton btn; // Play | Pause toggle button
private ImageView img; // Radio tower image that alternates between on and off
StreamService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Bind the view buttons to local variables
btn = findViewById(R.id.playPause);
img = findViewById(R.id.radioTower);
startStream();
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (service.isplaying()) {
Log.d("pause","Pause Playback");
} else {
Log.d("play", "Start Playback");
}
}
});
}
public void startStream() {
Intent serviceIntent = new Intent(MainActivity.this, StreamService.class);
serviceIntent.setAction(StreamService.ACTION_PLAY);
startService(serviceIntent);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
}
public void stopStream() {
if (service != null) {
try {
service.stop();
unbindService(mConnection);
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
} catch (IllegalArgumentException ex) {
stopService(new Intent(MainActivity.this, service.getClass()));
service = null;
ex.printStackTrace();
}
}
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder _service) {
StreamService.LocalBinder binder = (StreamService.LocalBinder) _service;
service = binder.getServiceInstance(); //Get instance of your service!
service.registerClient(MainActivity.this); //Activity register in the service as client for callabcks!
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
}
Service starts just fine, I just need to learn how to access the service object to implement the play pause functionality.
I have a fragment where i am using media player and using my own custom controller class. I am not being able to set controller.setMediaPlayer inside fragment. I have implemented VideoControllerView.MediaPlayerControl class in fragment.
My fragment class is :
public class HomeFragment extends Fragment implements SurfaceHolder.Callback, VideoControllerView.MediaPlayerControl {
#BindView(R.id.videoSurfaceContainer)
FrameLayout videoContainer;
#BindView(R.id.videoSurface)
SurfaceView videoSurface;
#BindView(R.id.progress)
ProgressBar progressBar;
#BindView(R.id.errorTv)
RelativeLayout relativeLayout;
#BindView(R.id.errorTextView)
TextView errorTextView;
public MediaPlayer player;
public VideoControllerView controller;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_home, container, false);
ButterKnife.bind(this, v);
player = new MediaPlayer();
controller = new VideoControllerView(getActivity());
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
progressBar.setVisibility(View.VISIBLE);
playVideo("http://202.166.200.170:8081/otv/aastha.stream/playlist.m3u8");
relativeLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
relativeLayout.setVisibility(View.GONE);
player.reset();
progressBar.setVisibility(View.VISIBLE);
playVideo("http://202.166.200.170:8081/otv/aastha.stream/playlist.m3u8");
} catch (Exception e) {
e.printStackTrace();
}
}
});
return v;
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
player.setDisplay(surfaceHolder);
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
public void playVideo(String link) {
try {
videoSurface.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (controller.isShowing())
controller.hide();
else
controller.show();
return false;
}
});
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer();
controller.setAnchorView((FrameLayout) getActivity().findViewById(R.id.videoSurfaceContainer));
player.start();
progressBar.setVisibility(View.GONE);
if (relativeLayout.isShown())
relativeLayout.setVisibility(View.GONE);
}
});
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(getActivity(), Uri.parse(link));
try {
player.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
progressBar.setVisibility(View.GONE);
errorMessage("Streaming Error");
player.reset();
errorTextView.setText(getResources().getString(R.string.error_msg_video));
return false;
}
});
player.setScreenOnWhilePlaying(true);
Log.d("after click", "last try");
} catch (Exception e) {
e.printStackTrace();
}
}
public void errorMessage(String message) {
try {
relativeLayout.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void start() {
}
#Override
public void pause() {
}
#Override
public int getDuration() {
return 0;
}
#Override
public int getCurrentPosition() {
return 0;
}
#Override
public void seekTo(int pos) {
}
#Override
public boolean isPlaying() {
return false;
}
#Override
public boolean canPause() {
return false;
}
#Override
public boolean isFullScreen() {
return false;
}
#Override
public void toggleFullScreen() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
if you see inside playVideo method inside setOnpreparedListener i am getting error in controller.setMediaPlayer() because i am not being able to pass the context here.
what can be done here to solve the error?
This is how we can use controller.setMediaPlayer()
// Implement MediaPlayer.OnPreparedListener
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout)
findViewById(R.id.videoSurfaceContainer));
player.start();
}
// End MediaPlayer.OnPreparedListener
This is example to use costume controller
If you want, you could get the context from there using HomeFragment.this.getContext(), like:
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(HomeFragment.this.getContext());
controller.setAnchorView((FrameLayout) getActivity().findViewById(R.id.videoSurfaceContainer));
player.start();
progressBar.setVisibility(View.GONE);
if (relativeLayout.isShown())
relativeLayout.setVisibility(View.GONE);
}
});
I just moved controller.setMediaPlayer(this); to onCreateView and it worked.
I'm trying to implement live stream radio by using fragment and background service, however every time I click to radio button on navigation drawer I couldn't reach the player because it generates one more and I can only control the second one. Here is my fragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_radio, container, false);
init(v);
ApiManager.getInstance().getRadioBroadcast(new ApiResponseLive.GetLiveBroadcastListener() {
#Override
public void onSuccess(StreamModel days) {
turnRadioOn(ApiManager.streamModel);
}
#Override
public void onFailure(String responseString) {
}
});
registerHandler(v);
return v;
}
private void turnRadioOn(StreamModel streamModel) {
HashMap<Integer, ArrayList<GenericStreamItem>> broadcastDays = new HashMap<>();
streamModel.setStreamAllArrays(broadcastDays);
BroadcastPagerAdapter radioPagerAdapter = new BroadcastPagerAdapter(getChildFragmentManager(), getContext(), TAG);
radioPager.setAdapter(radioPagerAdapter);
}
private void init(View v) {
radioPager = (ViewPager) v.findViewById(R.id.broadcastRadioPager);
radioTabLayout = (TabLayout) v.findViewById(R.id.tabsDays);
radioTabLayout.setupWithViewPager(radioPager);
radioPlay = (ToggleButton) v.findViewById(R.id.playButton);
radioScrollView = (ScrollView) v.findViewById(R.id.radioScroll);
}
private void start(String url) {
try {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setDataSource(url);
mp.prepareAsync();
mp.setOnCompletionListener(this);
Log.e("Radio::", "Working");
} catch (Exception e) {
Log.e("StreamAudioDemo", e.getMessage());
e.printStackTrace();
}
}
private void stop() {
try {
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void stopRadio() {
try {
Log.e("stopRadio::", "Pause");
mp.pause();
mp.stop();
mp.reset();
mp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
}
private void registerHandler(View v) {
radioPlay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Log.e("Toggle::", "Enabled");
radioService = new RadioService();
radioService.initMediaPlayer(ApiManager.RADIO_URL);
} else {
Log.e("Toggle::", "Disabled");
stop();
stopRadio();
radioService.onDestroy();
}
}
});
v.findViewById(R.id.radioBroadcast).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radioScrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
public class RadioService extends Service implements MediaPlayer.OnErrorListener {
public void initMediaPlayer(String url) {
// ...initialize the MediaPlayer here...
ApiManager.getInstance().getRadioURL(new ApiResponseLive.GetTVStreamUrlListener() {
#Override
public void onSuccess(String tvUrl) {
start(ApiManager.RADIO_URL);
mp.setOnErrorListener(RadioService.this);
}
#Override
public void onFailure(String responseString) {
}
});
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// ... react appropriately ...
// The MediaPlayer has moved to the Error state, must be reset!
mp.reset();
return false;
}
#Override
public void onDestroy() {
if (mp != null) mp.release();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
}
Here is how I call fragment:
RadioFragment radioFragment = new RadioFragment();
fragment = fm.findFragmentByTag("radio");
radioDrawer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (fragment == null) {
fm.beginTransaction()
.remove(fm.findFragmentById(R.id.activity_content))
.add(R.id.activity_content, radioFragment,
"radio").addToBackStack("main").commit();
} else {
fm.beginTransaction().replace(R.id.activity_content,
radioFragment, "radio");
}
fullView.closeDrawers();
}
});
Please, I need my streaming audio player to be controlled from two different fragments:
Radiofragment and AboutFragment.
and here's my radio fragment
public class RadioFragment extends Fragment implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener{
AudioManager am;
ImageButton btnPlay = null;
private boolean isPlaying;
private PlayerManager playerManager;
private View view;
public RadioFragment(boolean p, PlayerManager pmanager){
this.isPlaying = p;
this.playerManager = pmanager;
}
#Override
public View onCreateView(LayoutInflater l, ViewGroup container, Bundle onSavedInstance){
super.onCreateView(l, container, onSavedInstance);
view = l.inflate(R.layout.activity_radio, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
btnPlay = (ImageButton)view.findViewById(R.id.btnPlay);
addButtonListeners();
}
private void addButtonListeners()
{
btnPlay.setAlpha(155);
btnPlay.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
onClickBtnPlay(v);
}
});
}
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), RadioFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra)
{
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what)
{
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(MainActivity.TAG, sb.toString());
return true;
}
#Override
public void onPrepared(MediaPlayer mp)
{
mp.start();
}
#Override
public void onCompletion(MediaPlayer mp)
{
mp.stop();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent)
{
Log.d(MainActivity.TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
in my AboutFragment, I have a layout with a play/pause button and
protected void onClickBtnPlay(View v)
{
if (isPlaying){
playerManager.pause();
isPlaying = false;
}
else{
if (playerManager == null){
playerManager = new PlayerManager(getString(R.string.link_streaming_radio), AboutFragment.this);
}
playerManager.play();
isPlaying = true;
}
}
here is the class where I controll the player:
public class PlayerManager{
private String xmlUrl;
private String server;
private MediaPlayer mp;
public PlayerManager(Fragment owner)
{
this.owner = owner;
this.server = "";
}
public void play()
{
server = path_to_server;
playMusic();
}
public void pause()
{
mp.stop();
mp.reset();
}
private void playMusic()
{
Uri myUri = Uri.parse(this.server);
try
{
if (mp == null){
this.mp = new MediaPlayer();
}
else{
mp.stop();
mp.reset();
}
mp.setDataSource(owner.getActivity(), myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener((OnPreparedListener) this.owner);
mp.setOnBufferingUpdateListener((OnBufferingUpdateListener) this.owner);
mp.setOnErrorListener((OnErrorListener) this.owner);
mp.setVolume(100,100);
mp.prepareAsync();
Log.d(MainActivity.TAG, "Done");
}
catch (Throwable t)
{
Log.d(MainActivity.TAG, t.toString());
}
}
}
can it be done with this kind of implementation or I have to use another approach?
Because I tried to pass playerManager via constructor but it seems to be in other activity context
so i get class cast exceptions. I also tried to pass Radiofragment context and got some null pointer exceptions
both from this last catch block above.
I need some light here, please..
thank you in advance!
You should have a foreground Service, containing the PlayerManager. You will then send play/pause commands from any activity or fragment you want.
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.