【问题标题】:converting audio file to bytearray: no such file or directory将音频文件转换为字节数组:没有这样的文件或目录
【发布时间】:2018-10-31 05:01:24
【问题描述】:

我正在尝试将音频文件转换为字节数组。音频文件是通过附加文件获取的,因此它在 Uri 中

ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileInputStream fis;
    try {

        //FileInputStream = reading the file
          fis = new FileInputStream(new File(audioFxUri.getPath()));
          byte[] buf = new byte[1024];
          int n;
          while (-1 != (n = fis.read(buf)))
                 baos.write(buf, 0, n);
     } catch (Exception e) {
         e.printStackTrace();
     }

     byte[] bbytes = baos.toByteArray();

我遵循了this one 的代码,但是一旦我跑了。它给了我一个错误

W/System.err: java.io.FileNotFoundException: /external/audio/media/646818: open failed: ENOENT (No such file or directory)

我也尝试使用 MediaPlayer 播放它并将 Uri 作为其源

  MediaPlayer player = new MediaPlayer();
  player.setAudioStreamType(AudioManager.STREAM_MUSIC);
  player.setDataSource(AttachAudio.this,audioFxUri.toString());
  player.prepare();
  player.start();

确认音频文件是否正常工作。附言。成功了。

我做错了什么,为什么它没有转换为字节数组?

【问题讨论】:

  • 检查外部读取权限
  • @VineshChauhan 是的,我在清单上有权限。

标签: android arrays file uri


【解决方案1】:

您拥有的文件 Uri /external/audio/media/646818 不是实际的文件路径,因此它给出的是 FileNotFoundException

您需要从 URI 中获取绝对路径,然后相应地读取文件。

您可以使用以下代码:

public String getRealPathFromURI(Uri contentUri) 
{
     String[] proj = { MediaStore.Audio.Media.DATA };
     Cursor cursor = managedQuery(contentUri, proj, null, null, null);
     int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
     cursor.moveToFirst();
     return cursor.getString(column_index);
}

或参考 thisthis SO 链接了解其他选项/方法

【讨论】:

  • 嗨!当前使用外部存储,与数据库无关。但我也尝试了你提供的链接。 String path = audioFxUri.uri.toString() 似乎无法识别“.uri”
  • 尝试使用String path = audioFxUri.toString()
  • 在我的代码中我替换了 fis = new FileInputStream(new File(audioFxUri.getPath()));到 audioFxUri.getString() 但它仍然给出了同样的错误
  • 您也可以尝试其他选项吗?另外,我发现了另一个链接,更具体到音频,我觉得这与您的问题更相关:stackoverflow.com/questions/5913427/… 注意:它与 SQLite 数据库无关,但属于 ContentResolver
  • 感谢我尝试其他选项。我掌握了您发送的内容,并正在研究与它相关的其他内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2019-09-19
  • 1970-01-01
相关资源
最近更新 更多