简体   繁体   English

如何读取音频文件

[英]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. 在一个Android项目中,我正在将音频文件读取到InputStream然后将其写入设备上的另一个位置。 When reading, in.read(buffer) as shown in the snippet returns -1 . 读取时,如代码片段中所示的in.read(buffer)返回-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 . 但是它不能播放,因为文件为空,即大小为0 bytes What is the right way to read and write audio files in using InputStreams and OutputStreams ? 使用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());
}

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? 似乎您的代码在这里有问题,在初始化之前调用了newFile.getUri()吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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