从android中的服务器下载mp3文件 [英] Downloading an mp3 file from server in android

查看:15
本文介绍了从android中的服务器下载mp3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个应用程序,可以从服务器下载音乐文件,准确地说是 .mp3.由于我是 Android 开发领域的新手,所以我将感谢你们的任何帮助.我需要一些东西来开始,如果你能给我一些有用资源的链接,我将不胜感激.谢谢

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

推荐答案

如果您想从任何 url 播放 .mp3 文件,请按照 nik 建议的代码进行操作.

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

但是,如果您想从服务器下载文件并将其存储在 sdcard 或内部存储设备上的任何位置,请按照此代码操作,

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

清单权限:

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

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

这篇关于从android中的服务器下载mp3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆