I'm trying to play a sound file on button click but my sound URL comes form internet e.g http://www.example.com/sound.mp3. How can I play when button is clicked, using a Media Player.
Example: This is the way to Play Local file
b.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.mmmm);
mp.start();
}
});
I want play this sound http://www.example.com/sound.mp3 represent R.raw.mmmm , without downloading this sound.
Media Player has greate feature in android.You can handle all event that occurred.So this is the code to play a file(Either Local or Online Url)
String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
//You can show progress dialog here untill it prepared to play
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
//Now dismis progress dialog, Media palyer will start playing
mp.start();
}
});
mediaPlayer.setOnErrorListener(new OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// dissmiss progress bar here. It will come here when MediaPlayer
// is not able to play file. You can show error message to user
return false;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With