繁体   English   中英

如何读取音频文件

[英]How to read audio file

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

要学究,请使用:

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.

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