lilina
lilina

Reputation: 1

converting audio file to bytearray: no such file or directory

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?

Upvotes: 0

Views: 197

Answers (1)

Firoz Memon
Firoz Memon

Reputation: 4680

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

Upvotes: 2

Related Questions