java - android/java 如何从服务器响应中获取音频文件?

标签 java android audio

我正在制作一个应用程序,我必须从服务器下载音频文件并将其保存到 Android 手机。我能够使用响应处理程序并使用流字符串来获取二进制字符串。音频文件已下载,但文件大小较大,并且在记事本中打开音频文件时有附加(特殊字符)字符。

从服务器下载文件的代码

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://12.2.4.212:8080/v1/AUTH_fa32121dfaccsa12dascadsa2/audio/"+filename);
httpget.setHeader("X-Auth-Token","MIIKKgYJKoZIhvcNAQcCoIIKGzCCChcCAQExCTAHBgUrcNA=");
httpget.setHeader("Content-Type", "application/octet-stream");

ResponseHandler<String> rh = new BasicResponseHandler();
String response = httpclient.execute(httpget, responseHandler);

将文件保存到android的代码

InputStream is;
FileOutputStream fos;
File directory = new File(context.getExternalCacheDir(), "App/Audio");
File musicFile = new File(directory, filename);
if(!musicFile.exists()){
    try {
        cacheDirectory.mkdirs();
        musicFile.createNewFile();
        is = new ByteArrayInputStream(response.getBytes("UTF-8"));
        fos = new FileOutputStream(musicFile);
        byte[] buffer = new byte[is.available()];
        fos.write(buffer);
        is.close();
        fos.close();
    } catch (FileNotFoundException e){
        e.printStackTrace();
    } catch (IOException e){
        e.printStackTrace();
    }
}

预先感谢,我已经尝试了其他 stackoverflow 建议,但不起作用

最佳答案

您可以使用下载管理器

String dir = Environment.DIRECTORY_MUSIC;
            dir += "/klp";
            File fileDir = new File(dir);
            if (!fileDir.isDirectory()) {
                fileDir.mkdir();
            }

            Toast.makeText(DetailActivity.this, "Download song " + name,
                    Toast.LENGTH_SHORT).show();
            // Download File
            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));
            request.setDescription(nameFile);
            request.setTitle(name);
            // in order for this if to run, you must use the android 3.2 to
            // compile your app
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            }
            request.setDestinationInExternalPublicDir(dir, nameFile);

            // get download service and enqueue file
            DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
            manager.enqueue(request);

关于java - android/java 如何从服务器响应中获取音频文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21375597/

相关文章:

java - EHCACHE磁盘分配算法

android - 在android上获取蓝牙网络共享设备的IP地址

android - Android:处理KEYCODE_MEDIA_NEXT中断音乐播放

java - 无法包含带有 jsp 的 ContextMenu :include in ADF

Java类继承/接口(interface)实现原理

java - java.sql.date 的问题

Android 颜色资源 - 使一种颜色成为另一种颜色的别名

安卓首选项 : Dependencies

arrays - 通过从as3中的库文件制作数组来播放声音?

jquery - 当我需要大量声音文件时,如何快速加载网页?