Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 269
chethankumar Avatar asked Jan 06 '23 19:01

chethankumar


2 Answers

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**

like image 84
chethankumar Avatar answered Apr 01 '23 14:04

chethankumar


The ByteArrayOutputStream you create is kept in the memory. If you work with huge files, then your memory can limit your ability. This: java.lang.OutOfMemoryError: Java heap space question has a solution that might work for you, though it's probably not the best thing to keep 50MB in the memory.

To answer your other question, you can do the exact same thing:

public void convert(byte[] buf, String path) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(buf);
    FileOutputStream fos = new FileOutputStream(path);
    byte[] b = new byte[1024];

    for (int readNum; (readNum = bis.read(b)) != -1;) {
        fos.write(b, 0, readNum);
    }
}
like image 31
Gavriel Avatar answered Apr 01 '23 16:04

Gavriel