0

Im trying to convert an audio file to byte array. where the audio file is fetch through attach file so its in an 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();

i followed that code from this one but once i ran. It gave me an error

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

I also tried to play it with a MediaPlayer and place Uri as its Source

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

to make sure if the audio file is working or not. Ps. it worked.

Is there something wrong im doing as to why it didnt convert to byte array?

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
lilina
  • 1
  • 3

1 Answers1

2

The File Uri you have /external/audio/media/646818 is not an actual File Path, hence it is giving FileNotFoundException.

You need to get absolute path from the URI and then read the file accordingly.

You can either use below code:

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);
}

or Refer this or this SO link for other options/methods

Firoz Memon
  • 4,282
  • 3
  • 22
  • 32
  • Hi! currently using external storage and nothing related to the database. But i also tried the link u gave. String path = audioFxUri.uri.toString() doesnt seem to recognize ".uri" – lilina Oct 31 '18 at 05:24
  • Try using `String path = audioFxUri.toString()` – Firoz Memon Oct 31 '18 at 05:29
  • in my code i replace fis = new FileInputStream(new File(audioFxUri.getPath())); to audioFxUri.getString() but it still gave the same error – lilina Oct 31 '18 at 05:33
  • Could you try other options too? Also, I found another link, more specific to audio, which I feel is more related to your question: https://stackoverflow.com/questions/5913427/how-to-get-the-uri-from-mediastore-via-file-path **Note**: It is not related to SQLite database but is part of ContentResolver – Firoz Memon Oct 31 '18 at 05:44
  • thanks ill try out other options. i getting a grasp of what youve sent and am looking into other related stuff to it – lilina Oct 31 '18 at 06:03