4

I need to download a .mp3 or .m4a file from the server by using an URL, and then play that song.

Any ideas?

2 Answers 2

5

Try this code in your file:

USE

url = "your url name+filename.jpg,mp3,etc..."
FileName = "/sdcard/savefilename" // save in your sdcard


  try{
        java.io.BufferedInputStream in = new java.io.BufferedInputStream(new java.net.URL(url).openStream());
        java.io.FileOutputStream fos = new java.io.FileOutputStream(FileName);
        java.io.BufferedOutputStream bout = new BufferedOutputStream(fos,1024);
        byte[] data = new byte[1024];
        int x=0;
        while((x=in.read(data,0,1024))>=0){
            bout.write(data,0,x);               
        }
        fos.flush();
        bout.flush();
        fos.close();
        bout.close();
        in.close();
  }
    catch (Exception ex)
    {
     }

and after you want to use MediaPlayer and create object of mediaplayer in your activity and play.

mp.reset();
mp.start();

like this.

Hope this will help you a lot.

3
  • @Pintu..it helped me a lot..thanks for ur reply..Everything is fine but it is giving some warnings in Console as [2010-12-15 10:11:39 - ddms]ADB rejected shell command (ls -l /): [2010-12-15 10:11:54 - ddms]ADB rejected shell command (ls -l /): [2010-12-15 10:11:59 - ddms]ADB rejected shell command (ls -l /): [2010-12-15 10:18:14 - ddms]ADB rejected shell command (ls -l /): [2010-12-15 10:18:19 - ddms]ADB rejected shell command (ls -l /sdcard): ......... ........ can u please tell me what i have to do?
    – Venugopal
    Dec 15, 2010 at 4:55
  • 1
    something wrong with your code or virtual device. Because I am not getting any error from this code. Just check it once.
    – Pintu
    Dec 20, 2010 at 11:29
  • this code is nice but how to make this download process run in background??
    – cooldeep
    Feb 1, 2011 at 19:26
-4

There are plenty of questions of how to download a file in android. Just search.

On the other hand, you can use android's MediaPlayer to play the file from the internet without downloading it.

1
  • my task is to download the songs from server at starting and then play them locally. If u know how to do it in best way, can please guide me in that way?
    – Venugopal
    Dec 15, 2010 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.