Play a sound file from internet when a button is clicked [duplicate]
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 would like to play this sound locally, you have to download it first.
You just cannot "play something from the internet" as the machine which is playing that sound is your local machine. It needs to have a copy the that MP3.
After that, there might be ways to start playing before the download complete, but there will be a download anyway.
EDIT: AndroidDeveloper, in another reply of that page, gave you information about how to do streaming (+1!). This corresponds to what I've stated above, so it seems there IS a way to start playing before the download actually completes, even though this download will have happened at the end.
精彩评论