Android从服务器下载音频

Android从服务器下载音频,android,download,Android,Download,当我点击按钮时,我想通过url从我的服务器下载音频 我是如何做到的?要从服务器下载文件,可以使用以下代码 private class DownloadFile extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... url) { int count; try { URL url = new URL("url of yo

当我点击按钮时,我想通过url从我的服务器下载音频


我是如何做到的?

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

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;
}
私有类下载文件扩展异步任务{
@凌驾
受保护的字符串doInBackground(字符串…url){
整数计数;
试一试{
URL=新URL(“您的.mp3文件的URL”);
URLConnection conexion=url.openConnection();
conexion.connect();
//这将非常有用,以便您可以显示典型的0-100%进度条
int lenghtOfFile=conexion.getContentLength();
//下载文件
InputStream输入=新的BufferedInputStream(url.openStream());
OutputStream output=新文件OutputStream(“/sdcard/somewhere/nameoffile.mp3”);
字节数据[]=新字节[1024];
长总计=0;
而((计数=输入。读取(数据))!=-1){
总数+=计数;
//发布进度。。。。
出版进度(整数)(总计*100/长办公室);
输出.写入(数据,0,计数);
}
output.flush();
output.close();
input.close();
}捕获(例外e){}
返回null;
}
清单权限:

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

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

也请参考以下链接,它可能会帮助您:


您的问题不清楚。您想做什么?谢谢,先生。我想在单击按钮时通过url从我的服务器加载音频。