How to set continous MediaPlayer playback without interrupton after tilt? - java

Please I want to know how to set my MediaPlayer to playback continuously without stopping when activity screen rotates? The challenge I'm having now is that when playing is in progress and I happen to tilt the screen the music stops and will require another action to have it play again.
this is the part of which plays the music in my Activity
// setting up media players
public void play(View v) {
if (player == null) {
//then here, I sent the position of the chosen song in the intent extras.
//the get back the extra
int position = 0;
try{
position=getIntent().getIntExtra("soundfile",0);
}catch (Exception e)
{
e.printStackTrace();
}
String fileToPlay="song_"+position;
player = MediaPlayer.create(this, position);
Toast.makeText(this, "Hymn Tune Playing", Toast.LENGTH_SHORT ).show();
soundSeekBar = (SeekBar) findViewById(R.id.seekBar1);
soundSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser){
player.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
soundSeekBar.setProgress(player.getCurrentPosition());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
player.getCurrentPosition();
}
});
player.setLooping(true);
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
player.start();
Toast.makeText(this, "Playing Continues...", Toast.LENGTH_SHORT ).show();
soundThread = new Thread(this);
soundThread.start();
}
public void pause(View v) {
if (player != null) {
player.pause();
Toast.makeText(this, "Hymn Tune Paused", Toast.LENGTH_SHORT ).show();
}
}
public void stop(View v) {
stopPlayer();
}
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "Hymn Tune Stoped", Toast.LENGTH_SHORT ).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
#Override
public void run() {
int currentPosition = 0;
int soundTotal = player.getDuration();
soundSeekBar.setMax(soundTotal);
while (player != null && currentPosition < soundTotal){
try {
Thread.sleep(300);
currentPosition = player.getCurrentPosition();
}
catch (InterruptedException soundException){
return;
}
catch (Exception otherException){
return;
}
soundSeekBar.setProgress(currentPosition);
}
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}

You must move your playback code to background service, as those will run constantly while activity is stopped and restarted during tilting. Check out extensive guide to services here
https://developer.android.com/guide/components/services

Related

Handling volume buttons with screen locked

Currently, I'm working on my simple android studio script, and I must use volume down while the mobile screen is locked.
Please, take a look at my script:
public class MainActivity extends AppCompatActivity {
public MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BroadcastReceiver vReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
}
};
registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
event.startTracking();
initAudio(getApplicationContext(), "https://www.w3schools.com/html/horse.mp3");
return true;
}
return super.onKeyDown(keyCode, event);
}
public void initAudio(final Context context, String url) {
if (mediaPlayer == null) {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
killMediaPlayer();
}
});
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context, "Fail", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
}
}
public void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
What should I do to fix this issue? There are no errors, the script only works when I'm with my screen unlocked.
Can you help me with this?
Thank you very much.

Accessing a view from a service

So basically, i got a list view that shows a list of bands.
When i press on one of the bands in the list, it creates a band profile page via an adapter.
In this layout, i got a play button, which starts a MediaPlayer service and play a song.
So far, so good.
The problem is, im trying to update the seekBar, located in the band profile page (created by the adapter mentioned above), from the MediaPlayer service Java file, but i'm unable to reach it.
i'm trying to use :
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_singleband, null, false);
seekBar = (SeekBar) layout.findViewById(R.id.seekBarBand);
but it seems that it uses another "instance" of the view, and not the one i'm currently viewing.
Here is the full MusicService Java file:
public class MusicService extends Service {
SeekBar seekBar;
Handler handler;
Runnable runnable;
NotificationManager nMN;
TextView BandName;
String songLink;
String songName;
String bandName;
String SongPlaying="";
String BandPlaying="";
public static MediaPlayer mp;
public static Boolean mpState = true;
public static Boolean mpPause = false;
public static Boolean isPlaying = false;
#Override
public void onCreate() {
super.onCreate();
}
// Play Cycle for seekBar
public void PlayCycle(){
seekBar.setProgress(mp.getCurrentPosition());
if (mp.isPlaying()){
runnable = new Runnable() {
#Override
public void run() {
PlayCycle();
}
};
handler.postDelayed(runnable, 1000);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
songLink = intent.getStringExtra("SongLink");
songName = intent.getStringExtra("SongName");
bandName = intent.getStringExtra("BandName");
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.activity_singleband, null, false);
seekBar = (SeekBar) layout.findViewById(R.id.seekBarBand);
BandName = (TextView) layout.findViewById(R.id.singleBandNameView);
BandName.setText("Bla Bla");
System.out.print("Band Name : "+ BandName.getText() );
handler = new Handler();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean input) {
if (input){
mp.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
if (isPlaying && !songName.equals(SongPlaying) && !BandPlaying.equals(bandName)) {
Stop();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
Uri songUri = Uri.parse(songLink);
mp.setDataSource(getApplicationContext(), songUri);
SongPlaying = songName;
Toast.makeText(getApplicationContext(), "Please wait", Toast.LENGTH_SHORT).show();
isPlaying=true;
new prepare().execute();
}
catch (IOException e) {
e.printStackTrace();
}
}
else if (!isPlaying && !songName.equals(SongPlaying) && !BandPlaying.equals(bandName) ) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
Uri songUri = Uri.parse(songLink);
mp.setDataSource(getApplicationContext(), songUri);
SongPlaying = songName;
Toast.makeText(getApplicationContext(), "Please wait", Toast.LENGTH_SHORT).show();
new prepare().execute();
isPlaying=true;
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(getApplicationContext(), "Song is Already Playing", Toast.LENGTH_SHORT).show();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
handler.removeCallbacks(runnable);
}
/// Permanent Notification
private void showNotification() {
nMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n = new Notification.Builder(this)
.setContentTitle(songName)
.setContentText(bandName)
.setSmallIcon(R.drawable.ic_bandcamp)
//.addAction(R.drawable.ic_play_arrow_black_24dp, "button1", new pause())
.setOngoing(true)
.build();
nMN.notify(1, n);
}
/// PREPARE SONG TO PLAY //
public class prepare extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.prepare();
PlayCycle();
seekBar.setMax(mp.getDuration());
mp.start();
SongPlaying = songName;
isPlaying=true;
showNotification(); // show notification
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(getApplicationContext(),"Song Finished", Toast.LENGTH_LONG).show();
new stop().execute();
}
});
} catch (IOException io){ io.printStackTrace(); }
return null; }}
/// STOP PLAYING SONG //
public static void Stop()
{
mp.reset();
mp.release();
isPlaying=false;
}
public static class stop extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.reset();
mp.release();
isPlaying=false;
} catch (Exception io){ io.printStackTrace(); }
return null; }}
/// PAUSE PLAYING SONG//
public static class pause extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.pause(); }
catch (Exception io){ io.printStackTrace(); }
return null; }}
public static class start extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.start(); }
catch (Exception io){ io.printStackTrace(); }
return null; }}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
Would love to have some suggestions.
Thanks in advance.
Okey Firstly I suggest you to read more about Android Service classes. Secondly Do NOT place you visual components like a SeekBar or TextView in the Service because it doesn't make any sense. Service is just a background task and do not know about the UI. Since it's executed in the background you don't even need AsyncTask inside this so thirdly remove ALL AsyncTasks in your service and run their task like they don't need to be executed in the background.
So all what you have to do is create a Fragment/Activity for the UI, then bind your Fragment/Acitivity with your Service to communicate and update UI components.
The easiest way is make the Service a Singleton like it's done here:
public class MusicService extends Service {
private static MusicService instance = null;
public static MusicService getInstance() {
return instance;
}
Handler handler;
Runnable runnable;
NotificationManager nMN;
String songLink;
String songName;
String bandName;
String SongPlaying="";
String BandPlaying="";
public static MediaPlayer mp;
public static Boolean mpState = true;
public static Boolean mpPause = false;
public static Boolean isPlaying = false;
#Override
public void onCreate() {
instance = this;
super.onCreate();
}
// Play Cycle for seekBar
public void PlayCycle(){
seekBar.setProgress(mp.getCurrentPosition());
if (mp.isPlaying()){
runnable = new Runnable() {
#Override
public void run() {
PlayCycle();
}
};
handler.postDelayed(runnable, 1000);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
songLink = intent.getStringExtra("SongLink");
songName = intent.getStringExtra("SongName");
bandName = intent.getStringExtra("BandName");
handler = new Handler();
if (isPlaying && !songName.equals(SongPlaying) && !BandPlaying.equals(bandName)) {
Stop();
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
Uri songUri = Uri.parse(songLink);
mp.setDataSource(getApplicationContext(), songUri);
SongPlaying = songName;
Toast.makeText(getApplicationContext(), "Please wait", Toast.LENGTH_SHORT).show();
isPlaying=true;
new prepare().execute();
}
catch (IOException e) {
e.printStackTrace();
}
}
else if (!isPlaying && !songName.equals(SongPlaying) && !BandPlaying.equals(bandName) ) {
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
Uri songUri = Uri.parse(songLink);
mp.setDataSource(getApplicationContext(), songUri);
SongPlaying = songName;
Toast.makeText(getApplicationContext(), "Please wait", Toast.LENGTH_SHORT).show();
new prepare().execute();
isPlaying=true;
}
catch (IOException e) {
e.printStackTrace();
}
}
else {
Toast.makeText(getApplicationContext(), "Song is Already Playing", Toast.LENGTH_SHORT).show();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
mp.release();
handler.removeCallbacks(runnable);
}
/// Permanent Notification
private void showNotification() {
nMN = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification n = new Notification.Builder(this)
.setContentTitle(songName)
.setContentText(bandName)
.setSmallIcon(R.drawable.ic_bandcamp)
//.addAction(R.drawable.ic_play_arrow_black_24dp, "button1", new pause())
.setOngoing(true)
.build();
nMN.notify(1, n);
}
/// PREPARE SONG TO PLAY //
public class prepare extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.prepare();
PlayCycle();
seekBar.setMax(mp.getDuration());
mp.start();
SongPlaying = songName;
isPlaying=true;
showNotification(); // show notification
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(getApplicationContext(),"Song Finished", Toast.LENGTH_LONG).show();
new stop().execute();
}
});
} catch (IOException io){ io.printStackTrace(); }
return null; }}
/// STOP PLAYING SONG //
public static void Stop()
{
mp.reset();
mp.release();
isPlaying=false;
}
public static class stop extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.reset();
mp.release();
isPlaying=false;
} catch (Exception io){ io.printStackTrace(); }
return null; }}
/// PAUSE PLAYING SONG//
public static class pause extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.pause(); }
catch (Exception io){ io.printStackTrace(); }
return null; }}
public static class start extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
try {
mp.start(); }
catch (Exception io){ io.printStackTrace(); }
return null; }}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
return null;
}

progress bar for music player doesnt work and crashes

this is my code, i am almost certain the problem is with the while loop.
public void start(View view) {
int currentPosition = 0;
player = MediaPlayer.create(this, R.raw.sound);
player.start();
int total = player.getDuration();
progressBar.setProgress(0);
progressBar.setMax(player.getDuration());
while (player != null && currentPosition < total) {
// try {
// Thread.sleep(500);
currentPosition = player.getCurrentPosition();
// } catch (InterruptedException e) {
// return;
// } catch (Exception e) {
// return;
// }
progressBar.setProgress(currentPosition);
}
}
public void stop(View view) {
player.stop();
}
whether or not i have the sleep intervals my result is the same; the sound starts playing but i cant stop it, and the progress bar doesn't move.
i would appreciate some help
I used this code in my app for using seekBar with MediaPlayer. It implements Runnable to keep the seekBar updating as the music plays. Take a look at the code:
public class MainActivity extends Activity implements Runnable,
OnClickListener, OnSeekBarChangeListener {
private SeekBar seekBar;
private Button startMedia;
private Button stopMedia;
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.seekBar1);
startMedia = (Button) findViewById(R.id.button1);
stopMedia = (Button) findViewById(R.id.button2);
startMedia.setOnClickListener(this);
stopMedia.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setEnabled(false);
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(startMedia)) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.song2);
seekBar.setEnabled(true);
}
if (mp.isPlaying()) {
mp.pause();
startMedia.setText("play");
} else {
mp.start();
startMedia.setText("pause");
seekBar.setMax(mp.getDuration());
new Thread(this).start();
}
}
if (v.equals(stopMedia) && mp != null) {
if (mp.isPlaying() || mp.getDuration() > 0) {
mp.stop();
mp = null;
startMedia.setText("play");
seekBar.setProgress(0);
}
}
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
Thanks to: Sridhar Kulkarni

How to use Media Player In Android?

I have created demo for media player in Android.I'm facing the problem while start to run my application.When my app is run song is playing but not playing the full song it just start and immediately finish means it just start activity and immediately goes to resume() state.And when song is get over the i again restart my activity song is not playing from beginning it start from middle.I'm facing this problem last 1 week and i don't understand how to solve it .Please can any one help me.Here is my code.Thanks in advanced.
public class Audio_Activity extends Activity
{
private MediaPlayer mp = null;
PhoneStateListener phListener;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences. Editor prefsEdit = prefs.edit();
mp=MediaPlayer.create(Audio_Activity.this,R.raw.issaq_tera_by_vishu);
Log.e("Song is playing","in Mediya Player ");
mp.start();
mp.setLooping(false);
System.out.println("Media Plyer Is Start !!!");
prefsEdit.putBoolean("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
System.out.println("Media Plyer Is Complete !!!");
//mp.release();
prefsEdit.putBoolean("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener()
{
#Override
public void onCallStateChanged(int state, String incomingNumber)
{
if (state == TelephonyManager.CALL_STATE_RINGING)
{
if(mp!=null)
{
setPlayerButton(true, false, true);
if(mp.isPlaying())
{
mp.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null)
{
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void setPlayerButton(Boolean play, Boolean pause, Boolean stop){
btnStartStop.setEnabled(play);
if(play==true)
btnStartStop.setEnabled(true);
else
btnStartStop.setEnabled(false);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
#Override
public void onPause()
{
super.onPause();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = mp.getCurrentPosition();
Log.e("Current ","Position -> " + position);
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying)
{
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
mp.start();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onStop();
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
if(mp.isPlaying())
{
mp.pause();
System.out.println("Media Player is Pause/Stop click on Back button on Emulator!!!");
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
the starting from middle of the song problem is because you store the current progress of song in SharedPreferences and then at onResume() you start the player from the progressed position that stored at SharedPreferences
It's better to register for OnPreapredListener via MediaPlayer.setOnPreaparedListener and after preparation you start your media playback.
Official guide:
http://developer.android.com/guide/topics/media/mediaplayer.html
Please try to use bellow code.
void play() {
mediaPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.keytone);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
private void pause()
{
mediaPlayer.release();
}

Why won't this Java Android SHOUTcast MediaPlayer app code work?

String url = "http://91.121.140.11:8000/";
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare();
mediaPlayer.start();
I am using Android 4.0.3 to test this and have tried it on a physical device and the emulator. The app opens but I cannot hear anything. I thought they added support for SHOUTcast streams. Have I done something wrong?
I was having the same issue so I decided simply to try it on a real device (4.0.4). It worked. Seems like an emulator issue to me.
MediaPlayer mp;
#Override
public void onCreate(){
mp = new MediaPlayer();
mp.setOnPreparedListener(this);
}
public void prepareplayer(){
mp.setDataSource(Url);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d(TAG, "Preparing..");
mp.prepareAsync();
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.d(TAG, "Prepared");
mp.play();
}
I suggest you
test with other URL
try removing third line
I'm using this code for a shout cast stream works okay. Just need to add a controller using a surfaceview in XML.
private String shoutcastsource = "Your http:\\223.example.80.4003"
surfaceView = (SurfaceView)findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaController != null){
mediaController.show();
}
return false;
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(radiostation.this,
"Media Controls active lets mash it up", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(shoutcastsource);
mediaPlayer.prepare();
mediaController = new MediaController(this);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(radiostation.this,
"Radio Station off Air or no internet connection!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(radiostation.this,
"You are now connected to Ukn-Radio the home of the mash up", Toast.LENGTH_LONG).show();
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(surfaceView);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
finish();
}
}
Edit
Also make sure you allow internet access in your Android manifest:
<uses-permission android:name="android.permission.INTERNET" />

Categories

Resources