簡體   English   中英

android / java如何從服務器響應中獲取音頻文件?

[英]android/java how do you get audio file from a server response?

我正在制作一個應用程序,我必須從服務器下載音頻文件並將其保存到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建議,但沒有用

您可以使用DownloadManager

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM