簡體   English   中英

如何在Android中將視頻/音頻文件轉換為字節數組,反之亦然?

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

我試圖將音頻/視頻轉換為字節數組,反之亦然,使用下面的代碼能夠將音頻/視頻文件轉換為字節數組(請參見下面的代碼),但是無法轉換大文件(超過50MB的文件)沒有任何限制。 ? 如何將字節數組轉換為音頻/視頻文件? 請幫助我。

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

請幫助獲得結果

謝謝...在您的幫助下,我得到了解決方案,將字節轉換為文件(音頻/視頻),請參見以下代碼。

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包含路徑,用於播放音頻/視頻文件**

您創建的ByteArrayOutputStream保留在內存中。 如果使用大文件,則內存可能會限制您的能力。 這: java.lang.OutOfMemoryError:Java堆空間問題提供了一個可能對您有用的解決方案,盡管將50MB的內存留在內存中並不是最好的選擇。

要回答其他問題,您可以做完全相同的事情:

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