You may have seen that I have had a problem with creating a Media Player a few months back. Well I am trying to get to the next stage by getting it to work in a fragment but the app keeps on stopping/crashing on me. Can someone help me please? Here is my activity/fragment (code-behind) class
public class MediaPlayerNew extends Fragment implements
android.media.MediaPlayer.OnCompletionListener,
android.media.MediaPlayer.OnPreparedListener,
android.media.MediaPlayer.OnErrorListener,
android.media.MediaPlayer.OnBufferingUpdateListener{
private MediaPlayer mp = null;
private String TAG = getClass().getSimpleName();
private Button play;
private Button pause;
private Button stop;
private TextView txtVStatus;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_player, container, false);
return view;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
play = (Button) getActivity().findViewById(R.id.btnPlay);
pause = (Button) getActivity().findViewById(R.id.btnPause);
stop = (Button) getActivity().findViewById(R.id.btnStop);
//status = (TextView) findViewById(R.id.txtVStatus);
pause.setEnabled(false);
stop.setEnabled(false);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
}
private void play() {
//HTTP to BCRFM STREAM
Uri myUri = Uri.parse("http://37.187.193.36:8002");
try {
if (mp == null) {
this.mp = new android.media.MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(myUri.toString()); // Go to Initialized state)
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText("Welcome to BCRfm");
mp.start();
play.setEnabled(false);
pause.setEnabled(true);
stop.setEnabled(true);
}
private void pause() {
mp.pause();
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText("You have paused your feed to BCRfm");
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(true);
}
private void stop() {
mp.stop();
final TextView textViewToChange = (TextView) getActivity().findViewById(R.id.txtVStatus);
textViewToChange.setText(" ");
play.setEnabled(true);
pause.setEnabled(false);
stop.setEnabled(false);
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(android.media.MediaPlayer mp) {
stop();
}
public boolean onError(android.media.MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case android.media.MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case android.media.MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case android.media.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(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(android.media.MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}
There are issues with your code, and I will number them for clarity.
1) With methods onCreateView and onCreate, at least (check others!), place the keyword #Override above the methods declaration. Please compare sample codes in Google.
Failure to do this and perhaps the compiler would not consider it as overriding.
2) There is nothing wrong with
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
This is normal code.
3) Change from:
#Override
public void onDestroy() {
super.onDestroy();
}
TO:
#Override
public void onDestroy() {
stop();
super.onDestroy();
}
The main difference is calling stop() before onDestroy() call. When you're destructing, it's standard to call destroy/destruct after all the other codes.
And...you should stop the Media Player, otherwise it will still keep playing whatever even after the app exits.
Its okay, I fixed it.
I changed:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);......
to
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);..
And it works perfectly, only thing is when I want to switch from this fragment to another, the app crashes. Any tips?
Fixed it
Changed
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
to
#Override
public void onDestroy() {
super.onDestroy();
}
Related
I'm developing an app that plays a background music. The music is managed by a service that runs in background. In the Main activity, in the onCreate() method, the service starts with:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Background music service.
Intent musicServiceIntent = new Intent(this, BackgroundSoundService.class);
startService(musicServiceIntent);
final BackgroundSoundService bss = new BackgroundSoundService();
buttonStart = (Button) v.findViewById(R.id.button_start);
buttonStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bss.onStart();
}
});
buttonPause = (Button) v.findViewById(R.id.button_pause);
buttonPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bss.onPause();
}
});
buttonStop = (Button) v.findViewById(R.id.button_stop);
buttonStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bss.onStop();
}
});
}
}
}
The service is the following code:
BackgroundSoundService.java
public class BackgroundSoundService extends Service {
private static final String TAG = null;
static MediaPlayer mMediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.background_music);
mMediaPlayer.setVolume(1.0f, 1.0f);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
playMusic();
}
});
playMusic();
}
public void playMusic() {
mMediaPlayer.start();
}
/**
*
* #param arg0 -
* #return -
*/
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
/**
*
*/
public void onStart() {
Log.d("A", "onStart()");
if(!mMediaPlayer.isPlaying()) {
Log.d("A", "mMediaPlayer is not playing");
playMusic();
} else {
Log.d("A", "mMediaPlayer is playing");
}
}
/**
*
*/
public void onPause() {
Log.d("A", "onPause()");
if(mMediaPlayer.isPlaying()) {
Log.d("A", "mMediaPlayer is playing");
mMediaPlayer.pause();
} else {
Log.d("A", "mMediaPlayer is not playing");
}
}
/**
*
*/
public void onStop() {
Log.d("A", "onStop()");
if(mMediaPlayer.isPlaying()) {
Log.d("A", "mMediaPlayer is playing");
mMediaPlayer.stop();
} else {
Log.d("A", "mMediaPlayer is not playing");
}
}
/**
*
*/
#Override
public void onDestroy() {
Log.d("A", "onDestroy()");
mMediaPlayer.stop();
mMediaPlayer.release();
}
/**
*
*/
#Override
public void onLowMemory() {
}
}
Now, MainActivity has three buttons to control the music. SART Button, starts music, PAUSE Button, put the sound in pause and STOP Button, stops music. Each one executes the methos onStart(), on Pause() and onStop() in the BackgroundSoundService. The problem is if I press the START Button after the STOP Button, the log show me this error:
E/MediaPlayer: start called in state 0
E/MediaPlayer: error (-38, 0)
I try solve this implementing:
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
But did not work. Any suggestions? Thank you.
Posting MainActivity code helps us to give an exact solution without deviating you to random answers.
After .stop() , if you want it to start again you need to reset it.
public void onStop() {
Log.d("A", "onStop()");
if(mMediaPlayer.isPlaying()) {
Log.d("A", "mMediaPlayer is playing");
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.background_music);
} else {
Log.d("A", "mMediaPlayer is not playing");
}
}
EDIT
boolean isPrepared = false;
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
isPrepared = true;
}
});
public void playMusic() {
if(isPrepared){
mMediaPlayer.start();
isPrepared = false;
}
else{
Toast.makeText(getApplicationContext(),"Not prepared",LENGTH.SHORT)
.show();
}
}
Instead of mediaPlayer.create(), call new mediaplayer
Call prepare() and start() inside playMusic()
OR
prepareAsync() inside playMusic() and have onPreparedListener() calls start()
I used these codes from this reference. They want to click on button to play music and then click again to stop playing. (in their comment they said it was worked for them but hanging for me)
It is work just for first time. I mean for first click the music is playing. for second click the music is stop but for third click the phone emulator show this error:
unfortunately your program has stopped.
This is my code:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
mp.release();
}
else {
mp.start();
}
}
});
}
In onCreate initialize mp as :
mp = new MediaPlayer();
The error is you are releasing the media player object mp, which destroys the object, call reset method instead of release.
if (mp.isPlaying())
{
mp.stop();
mp.reset();
}
else {
mp = MediaPlayer.create(LegalActivity.this, R.raw.free1);
mp.start();
}
use this below code for play and pause the music:
public MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn=(Button) findViewById(R.id.btnRain);
//mp = MediaPlayer.create(this, R.raw.rain);
mp = MediaPlayer.create(MainActivity.this, R.raw.rain);
btn.setOnClickListener(new View.OnClickListener() {
#Override
//MediaPlayer mp = MediaPlayer.create(getApplicationContext(), R.raw.soundFileName);
// mp.start();
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
This is an AUDIO activity that works fine and it allows you to upload songs with a spinner.
public class AUDIO extends Activity{
Spinner spCanciones;
Button btnRep,btnGra,btnParar;
File audios;
String cancionSelec;
String arquivoGravar;
private MediaPlayer mediaplayer;
private boolean pause;
private MediaRecorder mediaRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio);
spCanciones=(Spinner)findViewById(R.id.spCanciones);
btnGra=(Button)findViewById(R.id.btnGra);
btnParar=(Button)findViewById(R.id.btnParar);
btnRep=(Button)findViewById(R.id.btnRep);
mediaplayer=new MediaPlayer();
enlazarSpinner();
//REPRODUCIR
btnRep.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
reproducir();
}
});
//PARAR
btnParar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mediaplayer.isPlaying())
mediaplayer.stop();
pause=false;
}
});
//GRABAR
btnGra.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
grabarAudio();
}
});
}
public void enlazarSpinner(){
final ArrayList<String>songs=new ArrayList<>();
audios=new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/AUDIO/");
String [] play=audios.list();
for (int i=0;i<play.length;i++)songs.add(play[i]);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, songs);
// Opcional: layout usuado para representar os datos no Spinner
adaptador.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Enlace do adaptador co Spinner do Layout.
spCanciones.setAdapter(adaptador);
// Escoitador
spCanciones.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
cancionSelec = songs.get(pos);
Log.i("Cancion", cancionSelec);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}); // Fin da clase anónima
}
public void reproducir(){
try {
mediaplayer.reset();
mediaplayer.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+cancionSelec);
mediaplayer.prepare();
mediaplayer.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MULTIMEDIA",e.getMessage());
}
}
public void grabarAudio(){
String timeStamp = DateFormat.getDateTimeInstance().format(
new Date()).replaceAll(":", "").replaceAll("/", "_")
.replaceAll(" ", "_");
mediaRecorder = new MediaRecorder();
arquivoGravar = Environment.getExternalStorageDirectory().getAbsolutePath()+"/AUDIO/"+ timeStamp + ".3gp";
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setMaxDuration(10000);
mediaRecorder.setAudioEncodingBitRate(32768);
mediaRecorder.setAudioSamplingRate(8000); // No emulador só 8000 coma
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setOutputFile(arquivoGravar);
try {
mediaRecorder.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
mediaRecorder.reset();
}
mediaRecorder.start();
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setMessage("GRAVANDO").setPositiveButton(
"PREME PARA PARAR",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
}
});
dialog.show();
enlazarSpinner();
}
#Override
protected void onPause() {
super.onPause();
if (mediaplayer.isPlaying()){
mediaplayer.pause();
pause = true;
}
}
#Override
protected void onResume() {
super.onResume();
if (pause) {
mediaplayer.start();
pause = false;
}
}
#Override
protected void onSaveInstanceState(Bundle estado) {
estado.putBoolean("MEDIAPLAYER_PAUSE", pause);
super.onSaveInstanceState(estado);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.putBoolean("MEDIAPLAYER_PAUSE", false);
pause = savedInstanceState.getBoolean("MEDIAPLAYER_PAUSE");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mediaplayer.isPlaying()) mediaplayer.stop();
if (mediaplayer != null) mediaplayer.release();
mediaplayer = null;
}
}
I am trying to play background music in simple game on Android using Services.
Using the link: Android Life Cycles
But this code doesn't work properly, onResumeActivity, onPauseActivity are called but the music keep running in background even when the onPauseActivity method is called.
The music keeps on playing while the app is in background.
is there any other way to play background music in an Android App/Game??
I think this code will work for you. Add this class (Enclosed in your activity class).
public class BackgroundMusic extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
MediaPlayer backgroundmusic = MediaPlayer.create(YourActivity.this, R.raw.yourbackgroundmusic);
player.setVolume(100,100);
player.setLooping(true);
player.start();
return null;
}
}
And create it
BackgroundMusic bm = new BackgroundMusic();
On onResume method:
public void onResume() {
super.onResume();
bm.execute(null);
}
And onPause method:
public void onPause() {
super.onPause();
bm.cancel(true);
}
Hope this help!
public class SoundGameBaseActivity extends Activity {
public static boolean isSoundPaused = false;
public static MediaPlayer mp;
protected static final String TAG = SoundGameBaseActivity.class.getName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
playMusic();
}
public static boolean isAppWentToBg = false;
public static boolean isWindowFocused = false;
public static boolean isMenuOpened = false;
public static boolean isBackPressed = false;
#Override
protected void onStart() {
Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
applicationWillEnterForeground();
super.onStart();
}
private void applicationWillEnterForeground() {
if (isAppWentToBg) {
//Google Analytics
MyApp.getInstance().trackScreenView("ApplicationActivated");
isAppWentToBg = false;
// Toast.makeText(getApplicationContext(), "App is in foreground",
// Toast.LENGTH_SHORT).show();
playMusic();
}
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop ");
applicationdidenterbackground();
}
public void applicationdidenterbackground() {
if (!isWindowFocused) {
isAppWentToBg = true;
Toast.makeText(getApplicationContext(),
"App is Going to Background", Toast.LENGTH_SHORT).show();
stopMusic();
}
}
public void TurnOnMusicAgain() {
}
void playMusic() {
if (mp == null) {
mp = MediaPlayer.create(this, R.raw.background1);
// mp.prepare();
mp.start();
mp.setLooping(true);
} else {
if (mp.isPlaying()) {
} else {
Log.e("", "coming back");
mp.start();
}
}
}
void stopMusic() {
if (mp != null)
mp.pause();
}
#Override
public void onBackPressed() {
if (this instanceof StartScreen) {
} else {
isBackPressed = true;
}
Log.d(TAG,
"onBackPressed " + isBackPressed + ""
+ this.getLocalClassName());
super.onBackPressed();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
isWindowFocused = hasFocus;
Log.e("Is Window Focus", "" + isWindowFocused);
if (isBackPressed && !hasFocus) {
isBackPressed = false;
isWindowFocused = true;
}
super.onWindowFocusChanged(hasFocus);
}
}
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 doing shoutcast streaming in my app. The app was playing the link on android emulator 2.2 but the same was not playing in device. Why? I am using galaxy tab 2.2. Any settings required to be done? Help is appreciated. Is there any special permission required in manifest?
public class radiog extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp = null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("http://stream.radiosai.net:8020/");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
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(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
}