Android从服务器下载音频[已关闭]

mxg2im7a  于 2022-11-03  发布在  Android
关注(0)|答案(1)|浏览(134)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

八年前就关门了。
Improve this question
我想下载音频通过网址从我的服务器当我点击按钮。
我是怎么做到的?

cbjzeqam

cbjzeqam1#

要从服务器下载文件,可以使用以下代码。

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;
}
}

信息清单权限:

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

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

也请参考以下链接,它可能会对您有所帮助:
how can i download audio file from server by url
How to download a file from a server and save it in specific folder in SD card in Android?

相关问题