Stream mp3 from link - android

i am trying to build a app that can stream mp3 content from the web. when i run this code i dont get any errors but there is no audio being played. Any help ? thanks
private MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
try {
mediaPlayer.setDataSource("my link.mp3"); //
mediaPlayer.prepareAsync();
//mediaPlayer.prepare(); //
if(! mediaPlayer.isPlaying())
{
mediaPlayer.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void initView() {
mediaPlayer = new MediaPlayer();
}
}

private MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
try {
mediaPlayer.setDataSource("my link.mp3"); //
// mediaPlayer.prepareAsync();
mediaPlayer.prepare();
// this mehthod block the UI if you want async operation then use mediaPlayer.prepareAsync();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}

Try this:
ProgressDialog progressDialog = ProgressDialog
.show(this, "Loading ", "Please Wait...");
progressDialog.setCancelable(false);
MediaPlayer player = new MediaPlayer();
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource("http://my link.mp3");
player.setOnErrorListener(this);
player.setOnPreparedListener(this);
player.prepareAsync();
} catch (IllegalArgumentException e) {
Toast.makeText(YourActivity.this,
"Internet Access is not Provided", 0).show();
e.printStackTrace();
} catch (IllegalStateException e) {
Toast.makeText(YourActivity.this,
"Internet Access is not Provided", 0).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(YourActivity.this,
"Internet Access is not Provided", 0).show();
e.printStackTrace();
}
#Override
public void onPrepared(MediaPlayer play) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
play.start();
}
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (player != null) {
player.release();
player = null;
}
return false;
}

Related

It has just one issue that it plays multiple songs if selected, rest everything works fine

the issue is, I have checked whether media player is null or not, if not I have applied release() method but still when I select another song to play, it plays new song but it doesn't stop the previous one. While playing next or previous on click also works fine. so why it is not detecting that mediaplayer is playing.
here is java code.
public class Musicplay extends AppCompatActivity implements View.OnClickListener {
Button play,next,previous;
TextView songmar;
SeekBar seekBar;
MediaPlayer mediaPlayer;
int position,idr;
Handler handler=new Handler();
Handler vindler=new Handler();
Uri uri;
int max;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playdisplay);
Intent i=getIntent();
position=i.getIntExtra("position",0);
play=findViewById(R.id.pause);
next=findViewById(R.id.next);
previous=findViewById(R.id.previous);
songmar=findViewById(R.id.songnamemar);
songmar.setSelected(true);
songmar.setText(Musiclist.songname.get(position));
seekBar=findViewById(R.id.seekBar);
if(mediaPlayer==null)
{
Log.d("null","null");
}
else {
if(mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
}
else {
mediaPlayer.release();
}
}
uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
mediaPlayer=MediaPlayer.create(Musicplay.this,uri);
seekBar.setMax(mediaPlayer.getDuration());
mediaPlayer.start();
max=mediaPlayer.getDuration();
play.setBackgroundResource(R.drawable.ic_pause);
Thread thread=new Thread(){
#Override
public void run() {
super.run();
int currentposition=0;
while (currentposition<max)
{
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
currentposition=mediaPlayer.getCurrentPosition();
seekBar.setProgress(currentposition);
}
}
};
thread.start();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
next.setOnClickListener(Musicplay.this);
play.setOnClickListener(Musicplay.this);
previous.setOnClickListener(Musicplay.this);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.stop();
mp.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
}
else
{
position=0;
}
uri = Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mp.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
});
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
seekBar.setMax(mp.getDuration());
max=mp.getDuration();
Log.d("seekvalue",String.valueOf(max));
}
});
}
#Override
public void onClick(View v) {
idr=v.getId();
Thread thread2=new Thread(){
#Override
public void run() {
super.run();
handler.post(new Runnable() {
#Override
public void run() {
switch (idr){
case R.id.pause:
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
play.setBackgroundResource(R.drawable.ic_play);
}
else {
play.setBackgroundResource(R.drawable.ic_pause);
mediaPlayer.start();
}
break;
case R.id.next:
mediaPlayer.stop();
mediaPlayer.reset();
if(position<(Musiclist.songname.size()-1)){
position=position +1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=0;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
case R.id.previous:
mediaPlayer.stop();
mediaPlayer.reset();
if(position>0){
position=position-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
else {
position=Musiclist.songname.size()-1;
Uri uri=Uri.parse(String.valueOf(new File(Musiclist.songpath.get(position))));
try {
mediaPlayer.setDataSource(Musicplay.this,uri);
} catch (IOException e) {
e.printStackTrace();
}
int a=0;
for(int i=0;i<150;i++)
{
a=a+1;
}
try {
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
play.setBackgroundResource(R.drawable.ic_pause);
songmar.setText(Musiclist.songname.get(position));
songmar.setSelected(true);
}
break;
}
}
});
}
};
thread2.start();
}
}
so do suggest reason why this error is taking place, and it is playing two or multiple song simultaneously.
all you have to do is, just declare mediaplayer variable public static and when you start activity to play song just check for media player is null or not and then release it

AndroidStudio MediaPlayer methods pause() and stop() doesnt work correctly

I'm working in a music player that download a File from firebase and init media player with this LOCALFILE. I've trying to STREAM_AUDIO with Media Player, but couldn't make pause() work properly with online streaming. Now,
pause/player button only call start() and doesn't pause(); stop() reinit audio immediately. How do I fix that?
Public class PerformanceActivity extends Activity {
private ImageButton playerPerf, stopPerf;
protected MediaPlayer mMediaPlayer;
protected ProgressDialog progressDialog;
private static String url = "https://firebasestorage.go....";
private File ARQUIVO_AUDIO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perfomance2);
playerPerf = findViewById(R.id.perfPlayId);
stopPerf = findViewById(R.id.perfStopId);
try {
executarProgressDialog();
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl(url);
final File localFile = File.createTempFile("audios", ".mp3");
Log.e("MEDIAPLAYER", "localfile criado com sucesso");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(localFile.toString());
Log.e("MEDIAPLAYER","Media player instanciado");
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
mMediaPlayer.prepareAsync();
} catch (IOException e) {
Log.e("MEDIAPLAYER",e.toString());
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PerfomanceActivity2.this, "ooops falha no download", Toast.LENGTH_LONG).show();
// progressDialog.dismiss();
Log.e("MEDIAPLAYER ERROR", e.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}
progressDialog.dismiss();
// Botao play/pause que executa o streaming
playerPerf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mMediaPlayer!=null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
Log.e("MEDIAPLAYER", "metodo pause chamado");
}
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
Log.e("MEDIAPLAYER", "start chamado");
}
}
}
});
// Pause o STREAMING e reinicializa o MediaPlayer
stopPerf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.prepare();
}
} catch (Exception e) {
Log.e("Audio erro", e.toString());
}
}
});
}
//libera espaço da memória quando a Activity é destruida
#Override
public void onDestroy() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
if (progressDialog != null) {
progressDialog.cancel();
}
}
super.onDestroy();
}
//Metodo que executa um ProgressDialog durante o download do audio
void executarProgressDialog() {
try {
progressDialog = new ProgressDialog(PerfomanceActivity2.this);
progressDialog.setMessage("Moluscos trabalhando...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle("Preparando meditação");
progressDialog.setCancelable(false);
progressDialog.show();
} catch (Exception e) {
Log.e("ProgressDialog Error", "Erro ao inicializar ProgressDialog");
}
}
}
There is an obvious logic problem in playerPerf.OnClickListener.
if (mMediaPlayer!=null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
Log.e("MEDIAPLAYER", "metodo pause chamado");
}
if (!mMediaPlayer.isPlaying()) { // <= always true because you pause it if not.
mMediaPlayer.start();
Log.e("MEDIAPLAYER", "start chamado");
}
}
The state mMediaPlayer.isPlaying wasn't separate correctly, which caused => if isPlaying then pauses it, directly considering if !isPlaying is always paused. So it always starts it no matter whether it was playing or not.
=> To solve it:
Just add a else instead of considering mMediaPlayer.isPlaying() twice.
if (mMediaPlayer!=null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
Log.e("MEDIAPLAYER", "metodo pause chamado");
} else { //<= change it to else
//if (!mMediaPlayer.isPlaying()) { // <= remove the second if
mMediaPlayer.start();
Log.e("MEDIAPLAYER", "start chamado");
}
}

Android MediaPlayer change live stream's URL

I have a problem with changing URL of live stream in the MediaPlayer instance. When I tap on a ListView item for a first time, live streaming is started and video is displayed, but if I click on another object in the ListView, stream is not changed, the same stream continues to play which was executed at first time.
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, VideoControllerView.MediaPlayerControl {
SurfaceView videoSurface;
MediaPlayer player;
VideoControllerView controller;
ArrayList<Channel> channels;
Channel clickedChannel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoSurface = (SurfaceView) findViewById(R.id.videoSurface);
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
controller = new VideoControllerView(this);
player = new MediaPlayer();
channels = new ArrayList<Channel>();
CreateChannels();
ListView lvMain = (ListView) findViewById(R.id.lvMain);
CustomAdapter adapter = new CustomAdapter(this, channels);
lvMain.setAdapter(adapter);
lvMain.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(LOG_TAG, "itemClick: position = " + position + ", id = "
+ id);
clickedChannel = channels.get(position);
}
}
}
PlayStream(clickedChannel.Streams[0].URL);
}
});
}
public void PlayStream(String URL) {
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// missed code
#Override
public boolean onTouchEvent(MotionEvent event) {
controller.show();
return false;
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
player.setDisplay(holder);
}
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(this);
controller.setAnchorView((FrameLayout) findViewById(R.id.videoSurfaceContainer));
player.start();
}
}
Solved my problem by recreating player instance every time
public void PlayStream(String URL) {
releaseMP();
try {
player = new MediaPlayer();
player.setDisplay(videoHolder);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(URL));
player.setOnPreparedListener(this);
player.prepareAsync();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void releaseMP() {
if (player != null) {
try {
player.release();
player = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMP();
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
}

Android app crashes in 5.0 and above when using MediaPlayer with url

I am developing an android app which play a mp3 songs by using a remote url. everything is working fine in android devices below api 5.0.But when starting app in samsung s5(5.1) it suddenly crashes
mu logcat is giving error "QCmediaPlayer mediaplayer is not present.Here is my code of Media Player
public class MainActivity2 extends Activity implements OnClickListener, OnPreparedListener {
private ProgressBar playSeekBar;
private final static String RADIO_STATION_URL ="https://aryaradio.s3.amazonaws.com/";
private String KEYNAME,encodedurl;
private List<String> playlistarray;
private List<MediaPlayer> mplayerList;
private ImageButton buttonPlay;
private List<S3ObjectSummary> playlist=null;
private ImageButton buttonStopPlay;
ProgressDialog progress;
URL url,currentsongurl;
private MediaPlayer player;
private AmazonS3Client mClient;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
playlistarray=new ArrayList<String>();
mplayerList=new ArrayList<MediaPlayer>();
if(isNetworkAvailable()) {
mClient = Util.getS3Client(MainActivity2.this);
initializeUIElements();
//new RefreshTask().execute();
buttonStopPlay.setVisibility(View.INVISIBLE);
} else {
new AlertDialog.Builder(MainActivity2.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
buttonStopPlay.setVisibility(View.INVISIBLE);
buttonPlay.setVisibility(View.INVISIBLE);
}
}
private void initializeUIElements() {
buttonPlay = (ImageButton) findViewById(R.id.Play);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (ImageButton) findViewById(R.id.Stop);
buttonStopPlay.setOnClickListener(this);
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
} else if (v == buttonStopPlay) {
stopPlaying();
finish();
startActivity(new Intent(MainActivity2.this, MainActivity2.class));
}
}
private void startPlaying() {
buttonPlay.setVisibility(View.INVISIBLE);
buttonStopPlay.setVisibility(View.VISIBLE);
progress = new ProgressDialog(this);
progress.setTitle("Message");
progress.setMessage("Loading Song ...");
progress.setCancelable(true);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.show();
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
progress.dismiss();
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
// player.setNextMediaPlayer(mplayerList.get(2));
stopPlaying();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
});
}
private void stopPlaying() {
killMediaPlayer();
initializeMediaPlayer(playlistarray);
buttonPlay.setVisibility(View.VISIBLE);
buttonStopPlay.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer(List<String> playlist) {
player = new MediaPlayer();
int noOfSongs=playlist.size();
String url = "https://aryaradio.s3.amazonaws.com/us-east-1:eb604ac1-c4e3-4226-bea8-22f214a6b0b0/RecordingArya-9459.mp3.null";
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(url);
player.setOnPreparedListener(this);
player.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
return false;
}
});
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.i("Buffering", "" + percent);
}
});
}
}

How to Play the online streaming radio in Android

I am developing one application where i want to play live stream radio. I have an url using which i will stream the radio and play. I have a play button by clicking which i want to play the radio. For that, i have written some code which is not at all working. Here is my code:
mp = new MediaPlayer();
try {
mp.setOnPreparedListener(this);
Log.d("Testing", "start111");
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
String url="xxxxxx";
mp.setDataSource(url);
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
Log.d("Testing", "Exception ::: 1111 "+e.getMessage());
} catch (IllegalStateException e) {
Log.d("Testing", "Exception ::: 2222 "+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.d("Testing", "IOException ::: 3333 "+e.getMessage());
e.printStackTrace();
}
Can anyone please help me??
You can find good information regarding radio streaming.
Github radio streaming example
and also there is a question in SOF which can also be helpful
Stackoverflow radio streaming example
Hope it will help. thanks
Try this.
public class RadioStream extends Activity {
private final static String stream = "http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio2_mf_p";
Button play;
MediaPlayer mediaPlayer;
boolean started = false;
boolean prepared = false;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio_stream);
play = (Button) findViewById(R.id.play);
play.setEnabled(false);
play.setText("Loading..");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (started) {
mediaPlayer.pause();
started = false;
play.setText("Play");
} else {
mediaPlayer.start();
started = true;
play.setText("Pause");
}
}
});
new PlayTask().execute(stream);
}
#Override
protected void onPause() {
super.onPause();
/* if(started)
mediaPlayer.pause();*/
}
#Override
protected void onResume() {
super.onResume();
/*if(started)
mediaPlayer.start();*/
}
#Override
protected void onDestroy() {
super.onDestroy();
// mediaPlayer.release();
}
private class PlayTask extends AsyncTask<String, Void, Boolean> {
#Override
protected Boolean doInBackground(String... strings) {
try {
mediaPlayer.setDataSource(strings[0]);
mediaPlayer.prepare();
prepared = true;
} catch (IOException e) {
e.printStackTrace();
}
return prepared;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
play.setEnabled(true);
play.setText("Play");
}
}
}
Please do try the code below and call the given method at the on create of your activity or at the onclick listener of your button. Remember to handle the stop and start button the imgV is an imageView for my button.
private MediaPlayer player;
private void startMediaPlayer() {
String url = "http:yoururl.com"; // your URL here
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(url);
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(isPlaying){
try {
mediaPlayer.prepareAsync();
progress.setVisibility(View.VISIBLE);
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
}
mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
}
boolean isPlaying = true;
private void startPlaying() {
isPlaying = true;
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
imgV.setImageResource(R.drawable.stop);
}
private void stopPlaying() {
if (mediaPlayer.isPlaying()) {
isPlaying = false;
mediaPlayer.stop();
mediaPlayer.release();
initializeMediaPlayer();
}
imgV.setImageResource(R.drawable.play);
}

Categories

Resources