简体   繁体   中英

How to read audio file

In an Android project I am reading an audio file into an InputStream and consequently write it to another location on the device. When reading, in.read(buffer) as shown in the snippet returns -1 . After running the app, I locate the file using the phone's file manager app to play. But it doesn't play because the file is empty, ie size is 0 bytes . What is the right way to read and write audio files in using InputStreams and 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());
}

to be pedantic, use:

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

And just make sure the path is correct and the file exists. Other than that, from the info you gave, I cannot think of anything else

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

Seem your code have problem here, newFile.getUri() is called before it init?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM