【问题标题】:How to read audio file如何读取音频文件
【发布时间】:2017-05-03 17:21:28
【问题描述】:

在一个 Android 项目中,我将音频文件读入 InputStream,然后将其写入设备上的另一个位置。读取时,sn -p 所示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());
}

【问题讨论】:

  • 避免使用硬编码的文件系统路径。参考这个链接developer.android.com/about/versions/…
  • @nandsito 指出。但这仅用于演示目的。
  • 您再次发布了相同的代码以及所有安全的内容。我建议你只发布代码来读取文件。专注于真正的问题。我也没有看到 file.exists() 和 file.length()。那应该在里面。没有安全。
  • 所以你不应该从一开始就谈论复制文件。仅阅读。
  • @greenapps 我已经更新了,希望更好。

标签: java android audio inputstream outputstream


【解决方案1】:

要迂腐,请使用:

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

只需确保路径正确且文件存在即可。除此之外,根据你提供的信息,我想不出别的了

【讨论】:

  • 谢谢,但结果是一样的。
【解决方案2】:
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() 在它初始化之前被调用?

【讨论】:

  • 这只是为了检查正在读取的源文件是否真的存在。 sn-p 已更新以消除这种混淆。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-27
  • 2013-11-30
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多