Downloading an mp3 file from server in android

2019-01-22 04:58发布

I am trying to create an app that can download music files, .mp3 to be precise, from the server.As I am a rookie in this Android Development field so I will appreciate any help from you guys. I need something to start on and I will really appreciate if u can give me some links for useful resources. Thanks

2条回答
Ridiculous、
2楼-- · 2019-01-22 05:36

If you want to play the .mp3 file from any url then follow the code suggested by nik.

But if you want to download a file form the server and store it in any place on sdcard or internal storage device then follow this code,

private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... urlParams) {
    int count;
    try {
        URL url = new URL("url of your .mp3 file");
        URLConnection conexion = url.openConnection();
        conexion.connect();
        // this will be useful so that you can show a tipical 0-100% progress bar
        int lenghtOfFile = conexion.getContentLength();

        // downlod the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.mp3");

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int)(total*100/lenghtOfFile));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {}
    return null;
}

EDIT: manifest permission:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
查看更多
孤傲高冷的网名
3楼-- · 2019-01-22 05:50

You can do it this way:

    try {
        MediaPlayer player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource("http://xty/MRESC/images/test/xy.mp3");
        player.prepare();
        player.start();

    } catch (Exception e) {
        // TODO: handle exception
    }

Manifest permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
查看更多
登录 后发表回答