Android download Audio from server [closed]

2020-06-30 04:14发布

I want to dowanload Audio via url from my server when I click the button.

How I do it ?

1条回答
男人必须洒脱
2楼-- · 2020-06-30 04:22

For DownloadFile from server you can use following code.

private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... url) {
    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;
}

manifest permission:

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

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

Also refer following links it may helps you :

how can i download audio file from server by url

Android:How to download the File from the server and save it in specific folder in sdcard

查看更多
登录 后发表回答