2014-01-27 67 views
0

我正在製作一個應用程序,我必須從服務器上下載音頻文件並將其保存到android手機中。我能夠使用響應處理程序獲取二進制字符串,並使用字符串進行流處理。音頻文件已下載,但文件大小較大,當您在記事本中打開音頻文件時,它具有其他(特殊字符)字符。android/java如何從服務器響應中獲取音頻文件?

代碼從服務器下載文件

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

謝謝,我已經嘗試其他計算器的建議,但不工作

回答

1

你可以使用下載管理器

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

嗨,它不工作..我的應用程序崩潰時下載文件.. – user3231112

+0

你可以告訴我你的logcat?因爲我的代碼工作正常。我正在使用我的應用程序(已發佈) – Luc

相關問題