Play a sound file from the Internet at the touch of a button

I am trying to play an audio file at the click of a button, but my audio URL comes from the Internet, for example, http://www.example.com/sound.mp3 . How to play when a button is pressed using Media Player.

Example:. This is a way to play a 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 to play this sound http://www.example.com/sound.mp3 introduce R.raw.mmmm without loading this sound.

+6
source share
2 answers

Media Player has a greate function in android. You can handle all events that have occurred. So this is the code to play the 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; } }); 
+18
source

If you want to play this sound locally, you must first download it.

You simply cannot β€œplay anything from the Internet,” because the machine that plays this sound is your local machine. He must have a copy of MP3.

After that, there may be ways to start playback before the download is complete, but there will be a download anyway.

EDIT : AndroidDeveloper, in another answer on this page, provided you with information on how to make threads (+1!). This is consistent with what I said above, so it seems that there is a way to start playing before the download actually completes, even if this download happens at the end.

0
source

Source: https://habr.com/ru/post/896112/


All Articles