2017-05-03 58 views
0

在Android項目中,我正在將音頻文件讀取到InputStream中,並將其寫入設備的其他位置。閱讀時,in.read(buffer)如片段所示返回-1。運行應用程序後,我使用手機的文件管理器應用程序找到該文件進行播放。但它不起作用,因爲該文件是空的,即大小爲0 bytes。在使用InputStreamsOutputStreams時,讀取和寫入音頻文件的正確方法是什麼?如何讀取音頻文件

try { 
DocumentFile newFile = pickedDir.createFile("audio/mp3", "New File"); 
OutputStream out = getContentResolver().openOutputStream(newFile.getUri()); 
InputStream in = new FileInputStream("/storage/emulated/0/beat.mp3"); 
// To check whether the source file exists 
File testFile = File("/storage/emulated/0/beat.mp3"); 
Log.d("App", "exists: " + testFile.exists() + " len: " + testFile.length());//exists: true len: 0 
byte[] buffer = new byte[1024]; 
int read; 
while ((read = in.read(buffer)) != -1) { 
     out.write(buffer, 0, read); 
} 
    in.close(); 
    out.flush(); 
    out.close(); 
} catch (Exception e) { 
    Log.d("Exception ", e.getMessage()); 
} 
+0

避免使用硬編碼的文件系統路徑。請參閱此鏈接https://developer.android.com/about/versions/android-4.2.html#MultipleUsers – nandsito

+0

@nandsito注意。但是,這僅用於演示目的。 – Godfred

+0

您再次發佈相同的代碼與所有安全的東西。我建議你只發布代碼來閱讀文件。專注於真正的問題。我也沒有看到file.exists()和file.length()。這應該是在它。沒有安全。 – greenapps

回答

0

是迂腐,用途:

FileInputStream in = new FileInputStream("/storage/emulated/0/beat.mp3"); 

而且只需確保路徑是正確的,該文件存在。除此之外,從你給的信息,我想不出別的

+0

謝謝,但結果是一樣的。 – Godfred

0
OutputStream out = getContentResolver().openOutputStream(newFile.getUri()); 
InputStream in = new FileInputStream("/storage/emulated/0/beat.mp3"); 
File newFile = File("/storage/emulated/0/beat.mp3"); 

好像你的代碼有問題就在這裏,newFile.getUri()被調用它初始化之前?

+0

這只是爲了檢查源文件是否真的存在。該片段已更新以消除該混淆。 – Godfred

相關問題