[英]How to read audio file
在一個Android項目中,我正在將音頻文件讀取到InputStream
然后將其寫入設備上的另一個位置。 讀取時,如代碼片段中所示的in.read(buffer)
返回-1
。 運行該應用程序后,我使用手機的文件管理器應用程序查找該文件以進行播放。 但是它不能播放,因為文件為空,即大小為0 bytes
。 使用InputStreams
和OutputStreams
讀寫音頻文件的正確方法是什么?
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());
}
要學究,請使用:
FileInputStream in = new FileInputStream("/storage/emulated/0/beat.mp3");
並確保路徑正確並且文件存在。 除此之外,從您提供的信息中,我再也想不到
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()嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.