How to convert video/audio file to byte array and vice versa in android.?

chethankumar picture chethankumar · Jan 21, 2016 · Viewed 22.5k times · Source

Am trying to convert audio/video to byte array and vice versa, using below code am able converting audio/video files to byte array(see below code) but am fail to convert large file(more then 50MB files) is there any limit.? how to convert byte array to audio/video file.? kindly help me out.

public byte[] convert(String path) throws IOException {

    FileInputStream fis = new FileInputStream(path);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] b = new byte[1024];

    for (int readNum; (readNum = fis.read(b)) != -1;) {
        bos.write(b, 0, readNum);
    }

    byte[] bytes = bos.toByteArray();

    return bytes;
}

Kindly help out to get the result

Answer

chethankumar picture chethankumar · Jan 22, 2016

Thanks... with your help i got solution, to convert the bytes to file(audio/video), see below code.

private void convertBytesToFile(byte[] bytearray) {
    try {

        File outputFile = File.createTempFile("file", "mp3", getCacheDir());
        outputFile.deleteOnExit();
        FileOutputStream fileoutputstream = new FileOutputStream(tempMp3);
        fileoutputstream.write(bytearray);
        fileoutputstream.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

**File outputFile = File.createTempFile("file", "mp3", getCacheDir());

outputFile contains the path, use that to play your audio/video file**