简体   繁体   English

如何在Android中将视频/音频文件转换为字节数组,反之亦然?

[英]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.? 我试图将音频/视频转换为字节数组,反之亦然,使用下面的代码能够将音频/视频文件转换为字节数组(请参见下面的代码),但是无法转换大文件(超过50MB的文件)没有任何限制。 ? 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 请帮助获得结果

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()); ** File outputFile = File.createTempFile("file", "mp3", getCacheDir());

outputFile contains the path, use that to play your audio/video file** outputFile包含路径,用于播放音频/视频文件**

The ByteArrayOutputStream you create is kept in the memory. 您创建的ByteArrayOutputStream保留在内存中。 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. 这: java.lang.OutOfMemoryError:Java堆空间问题提供了一个可能对您有用的解决方案,尽管将50MB的内存留在内存中并不是最好的选择。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM