Android从服务器下载音频

use*_*340 -2 android download

我想点击按钮时从我的服务器通过URL下载音频.

我是怎么做到的

Har*_*shi 6

对于服务器的DownloadFile,您可以使用以下代码.

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;
}
Run Code Online (Sandbox Code Playgroud)

明显许可:

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

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
Run Code Online (Sandbox Code Playgroud)

另请参阅以下链接,它可以帮助您:

我如何通过网址从服务器下载音频文件

Android:如何从服务器下载文件并将其保存在SD卡的特定文件夹中