Live audio stuttering in mediaplayer()? - android

I am new to android. I am making a live audio streaming app(streams from a URL). As soon as I hit play, the audio plays but there is a stuttering about every half second. I checked the live audio URL on my computer and it plays perfectly. And I checked it in another audio streaming app I am making, using the same emulator, and it plays perfectly there too. The streaming file is .mp3. I have added the code.
public class StreamAudioFromUrlSampleActivity extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{
private Button btn_play,
btn_pause,
btn_stop;
//private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengt
hOfAudio;
private final String URL = "**some url**";
//private final Handler handler = new Handler();
/*private final Runnable r = new Runnable() {
#Override
public void run() {
//updateSeekProgress();
}
};*/
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();mediaPlayer = new MediaPlayer();
}
private void init() {
btn_play = (Button)findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button)findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button)findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
//seekBar = (SeekBar)findViewById(R.id.seekBar);
//seekBar.setOnTouchListener(this);
//mediaPlayer.setOnBufferingUpdateListener(this);
//mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
//seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
//SeekBar tmpSeekBar = (SeekBar)v;
//mediaPlayer.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress() );
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
//lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
Log.e("Error", "error"+e);
}
switch (view.getId()) {
case R.id.btn_play:
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
//updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
//seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100));
// handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
mediaPlayer.stop();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
mediaPlayer.release();
//seekBar.setProgress(0);
}
private void pauseAudio() {
mediaPlayer.pause();
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {try{
Thread.sleep(10000);}catch(InterruptedException x){}
mediaPlayer.start();
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
}

Related

Android MediaPlayer with SurfaceView Fails on Prepare() Method

I am trying to build a video player using surface view and media player. My data source is an online video and I have enabled internet permission in manifest.
However, the video does not pay but throws a warning about prepare method without any hint at what the problem is like below:
W/System.err: at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1188)
at in.sashi.androidvideoplayer.MainActivity.surfaceCreated(MainActivity.java:64)
here's my code for this purpose:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, View.OnClickListener {
private static final String TAG = MainActivity.class.getSimpleName();
private SurfaceView surfaceView;
private ImageView playIV, backIV;
private TextView videoNameTV;
private MediaPlayer mediaPlayer;
private SurfaceHolder holder;
// private static final String VIDEO_URL = "https://www.youtube.com/watch?v=vEVd0QMjCc8";
private static final String VIDEO_URL = "http://mic.duytan.edu.vn:83/FINAL.mp4";
private static final String VIDEO_NAME = "FALL HARDER | BASKETBALL MOTIVATION";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
surfaceView = findViewById(R.id.surfsceView);
playIV = findViewById(R.id.playIV);
backIV = findViewById(R.id.backIV);
videoNameTV = findViewById(R.id.videoNameTV);
videoNameTV.setText(VIDEO_NAME);
backIV.setOnClickListener(this);
playIV.setOnClickListener(this);
holder = surfaceView.getHolder();
holder.addCallback(this);
surfaceView.setKeepScreenOn(true);
mediaPlayer = new MediaPlayer();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource(VIDEO_URL);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.backIV:
onBackPressed();
break;
case R.id.playIV:
if (mediaPlayer.isPlaying()){
Log.d(TAG, "Pause Clicked");
mediaPlayer.pause();
playIV.setImageResource(R.drawable.play);
} else {
Log.d(TAG, "Play Clicked");
mediaPlayer.start();
playIV.setImageResource(R.drawable.pause);
}
break;
}
}
#Override
protected void onPause() {
super.onPause();
collect();
}
private void collect() {
if (mediaPlayer != null){
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Can anyone help me to figure this out? Thanks.
Use mediaplayer object which is being defined globally.
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
How about this?
#Override
public void surfaceCreated(SurfaceHolder holder) {
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource(VIDEO_URL);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}

MediaPlayer.setOnCompletionListener not executing

public class MainActivity extends AppCompatActivity
implements View.OnClickListener {
private MediaPlayer mediaPlayer;
private ImageButton playBtn,previousBtn,forwardBtn,rewindBtn,nextBtn;
private SeekBar seekBar;
private int[] songsName = {R.raw.song1,R.raw.song2,R.raw.song3,R.raw.song4};
private int songPosition=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekBar = (SeekBar) findViewById(R.id.songProgressBar);
seekBar.setClickable(false);
seekBar.setEnabled(false);
playBtn = (ImageButton) findViewById(R.id.play);
playBtn.setOnClickListener((View.OnClickListener)this);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if(mediaPlayer != null && b){
mediaPlayer.seekTo(i);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
forwardBtn = (ImageButton) findViewById(R.id.forward);
forwardBtn.setOnClickListener((View.OnClickListener)this);
rewindBtn = (ImageButton) findViewById(R.id.rewind);
rewindBtn.setOnClickListener((View.OnClickListener)this);
nextBtn = (ImageButton) findViewById(R.id.next);
nextBtn.setOnClickListener((View.OnClickListener)this);
previousBtn = (ImageButton) findViewById(R.id.previous);
previousBtn.setOnClickListener((View.OnClickListener)this);
subView = (SubtitleView) findViewById(R.id.subs_box);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaplayer) {
Toast.makeText(getApplicationContext(),"Media Player End",Toast.LENGTH_LONG).show();
nextSong();
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.play:
playSong();
break;
case R.id.forward:
forwardSong(5000);
break;
case R.id.rewind:
rewindSong(5000);
break;
case R.id.next:
if(mediaPlayer !=null)
nextSong();
break;
case R.id.previous:
previousSong();
break;
}
}
public void playSong(){
imageName = (String) playBtn.getTag();
if(imageName.equals("play")) {
playBtn.setTag("stop");
//mediaPlayer = MediaPlayer.create(this, R.raw.chalisa);
Log.d(TAG,""+songPosition);
prepareMediaPlayer(songPosition);
seekBar.setMax(mediaPlayer.getDuration());
seekUpdation();
seekBar.setEnabled(true);
playBtn.setImageResource(R.drawable.stop);
}else{
playBtn.setImageResource(R.drawable.play);
playBtn.setTag("play");
mediaPlayer.pause();
mediaPlayer = null;
seekBar.setProgress(0);
seekBar.setEnabled(false);
subView.setText("");
}
}
public void forwardSong(int time){
if(mediaPlayer != null){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() + time);
}
}
public void rewindSong(int time){
if(mediaPlayer != null){
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition() - time);
}
}
public void nextSong(){
songPosition++;
if(songPosition < songsName.length){
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
songPosition = 0;
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}
}
public void previousSong(){
songPosition--;
if (songPosition != -1){
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}else{
mediaPlayer.pause();
seekBar.setProgress(0);
mediaPlayer.seekTo(0);
songPosition = 0;
mediaPlayer = null;
prepareMediaPlayer(songPosition);
}
}
public void prepareMediaPlayer(int songPosition){
mediaPlayer = MediaPlayer.create(this, songsName[songPosition]);
mediaPlayer.start();
subView.setPlayer(mediaPlayer);
subView.setSubSource(subTitleName[songPosition], MediaPlayer.MEDIA_MIMETYPE_TEXT_SUBRIP);
}
public void seekUpdation() {
if(mediaPlayer != null) {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
myHandler.postDelayed(run, 1000);
}
}
Runnable run = new Runnable() {
#Override public void run()
{
seekUpdation();
}
};
media player on completion not working, not able to print the log also.
My intention is to play the next song once the current song is completed, but i am not able to check the song is completed or not.
In the logcat, it is showing the below warning
W/MediaPlayer-JNI(16888): MediaPlayer finalized without being released.
not showing any error in the logcat......
What may be the issue?
Anything wrong with the MediaPlayer.onCreate?
setOnCompletionListener Always Work after Allocating Media Resources.
remove It From OnCreate Method And
add this listener to you Method PlaySong() after Preparing You Media Player..
It May Work.
public void playSong(){
imageName = (String) playBtn.getTag();
if(imageName.equals("play")) {
playBtn.setTag("stop");
//mediaPlayer = MediaPlayer.create(this, R.raw.chalisa);
Log.d(TAG,""+songPosition);
prepareMediaPlayer(songPosition);
seekBar.setMax(mediaPlayer.getDuration());
seekUpdation();
seekBar.setEnabled(true);
playBtn.setImageResource(R.drawable.stop);
}else{
playBtn.setImageResource(R.drawable.play);
playBtn.setTag("play");
mediaPlayer.pause();
mediaPlayer = null;
seekBar.setProgress(0);
seekBar.setEnabled(false);
subView.setText("");
}
myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do what ever you want
}
});
}
And Also This mediaPlayer = MediaPlayer.create(this, songsName[songPosition]); add Only Single time For Selected Song After Play do not create again..
then Again Create When You Are Doing Nextsong.

How to prepare mediaplayer in android while another playing?

I using MediaPlayerto play video from http stream is any solution to prepare second media player with another http url while first one still playing?
I want to play two videos without black screen between them, when first one end second start immediately.
Here is my code:
public class VideoActivity extends Activity implements SurfaceHolder.Callback {
private MediaPlayer mediaPlayer;
private SurfaceHolder surfaceHolder;
private SurfaceView playerSurfaceView;
private String videoSrc = "http://192.168.1.101:8090/api/video/";
private String android_id;
private MediaPlayer next;
private static boolean firstCall = true;
private String secondVideoSrc = "http://192.168.1.101:8090/api/secondvideo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
playerSurfaceView = (SurfaceView)findViewById(R.id.playersurface);
surfaceHolder = playerSurfaceView.getHolder();
surfaceHolder.addCallback(this);
GetDeviceId();
videoSrc += android_id;
secondVideoSrc += android_id;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
prepareVideoPlayer();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private void GetDeviceId() {
android_id = Settings.Secure.getString(getBaseContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
}
private void prepareVideoPlayer() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setDataSource(this, Uri.parse(videoSrc));
mediaPlayer.setScreenOnWhilePlaying(true);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
if(firstCall) {
mediaPlayer.start();
firstCall = false;
}
new AsyncPrepareNext().execute();
}
});
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
next.start();
}
});
}
catch(Exception ex) {
}
}
private void prepareNext() {
try {
next = new MediaPlayer();
next.setDisplay(surfaceHolder);
next.setDataSource(this, Uri.parse(secondVideoSrc));
next.setScreenOnWhilePlaying(true);
next.prepareAsync();
next.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
next.setAudioStreamType(AudioManager.STREAM_MUSIC);
next.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
}
});
}
catch(Exception ex) {
}
}
private class AsyncPrepareNext extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
prepareNext();
return null;
}
}
}
When i run this first video starts for 2 or 3 seconds and then stop with some errors like media server died, audio flinger died, error (100,0), error (38,0)
You'll probably need to implement the OnPreparedListener() and OnCompletedListener() to accomplish this and you might need 2 media players for it as well.
#Override
public void onPrepared(MediaPlayer mp){
// Set Video Source for second video
mp.setDataSource(path);
// Prepare second video
mp.prepareAsync();
}
#Override
public void onCompletion(MediaPlayer mp){
// Start second video here
mp.start();
}
and set them like this:
mediaPlayer.setOnPreparedListener(new OnPreparedListener());
mediaPlayer.setOnCompletedListener(new OnCompletionListener());

Playing audio file in android

I got stuck with one requirement i need to play a media file in android.I will post the screen shot of the page
Actual requirement is the user wants to play the audio file in his recordings list.The recordings list are shown through list adapter.I want to display the play progress of the audio file on the same page(as like shown in the screen shot).
Iam pasting the code which i have tried.
public class RecordingActivity extends ListActivity implements MediaPlayerControl {
MediaPlayer mMediaPlayer;
MediaController mMediaController;
Handler mHandler;
String OUTPUT_FILE;
RelativeLayout rl;
Context context = null;
Point p;
static final String[] recordings = new String[] {"Example1","Example2",
"Example3","Example4","Example5" };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new FirstAdapter(this, recordings));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
showPopup(RecordingActivity.this, p);
// get selected items
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mHandler = new Handler();
mMediaController.setMediaPlayer(RecordingActivity.this);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/recorder.mp3";
try{
mMediaPlayer.setDataSource(OUTPUT_FILE);
mMediaPlayer.prepare();
}
catch(Exception e){
}
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(10000);
mMediaPlayer.start();
mMediaController.setEnabled(true);
}
});
}
});
}
private void showPopup(final Activity context, Point p) {
int popupWidth = 200;
int popupHeight = 150;
// Inflate the popup_layout.xml
RelativeLayout viewGroup = (RelativeLayout) context.findViewById(R.id.reviewlist);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = layoutInflater.inflate(R.layout.activity_play, viewGroup);
// Creating the PopupWindow
final PopupWindow popup = new PopupWindow(context);
popup.setContentView(layout);
popup.setWidth(popupWidth);
popup.setHeight(popupHeight);
popup.setFocusable(true);
// Some offset to align the popup a bit to the right, and a bit down, relative to button's position.
int OFFSET_X = 30;
int OFFSET_Y = 30;
// Clear the default translucent background
popup.setBackgroundDrawable(new BitmapDrawable());
// Displaying the popup at the specified location, + offsets.
popup.showAtLocation(layout, Gravity.NO_GRAVITY,p.x+OFFSET_X,p.y+OFFSET_Y);
// Getting a reference to Close button, and close the popup when clicked.
ImageButton close = (ImageButton) layout.findViewById(R.id.close);
Button b1 =(Button) layout.findViewById(R.id.button1);
Button b2 =(Button) layout.findViewById(R.id.button2);
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
popup.dismiss();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
mMediaController.show();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show();
return false;
}
}
The problem am facing is i am able to play the audio file ,but it is not showing any popup layout.
Media player
MediaPlayer mp = new MediaPlayer();
// Set data source -
setDataSource("/sdcard/path_to_song");
// Play audio
mp.start();
// Pause audio
mp.pause();
// Reset mediaplayer
mp.reset();
// Get song length duration - in milliseconds
mp.getDuration();
// Get current duration - in milliseconds
mp.getCurrentDuration();
// Move song to particular second - used for Forward or Backward
mp.seekTo(positon); // position in milliseconds
// Check if song is playing or not
mp.isPlaying(); // returns true or false
Hope this will give you some solution. Refer this link. It will solve your problem
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this);
mMediaController.setMediaPlayer(PlayAudioActivity.this);
mMediaController.setAnchorView(findViewById(R.id.audioView));
String audioFile = "" ;
try {
mMediaPlayer.setDataSource(audioFile);
mMediaPlayer.prepare();
} catch (IOException e) {
System.out.println("Error in playing audio");
}
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(10000);
mMediaPlayer.start();
}
});
}
});
}
if you have done this then.
#Override
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100) / mMediaPlayer.getDuration();
return percentage;
}
#Override
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
if(mMediaPlayer.isPlaying())
mMediaPlayer.pause();
}
#Override
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show();
return false;
}
}
public class PlayAudioActivity extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
private Handler mHandler = new Handler();
use this .

Shoutcast streaming not working in android device 2.2

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 + "%");
}
}

Categories

Resources