如何在 android. 中将 video/audio 文件转换为字节数组,反之亦然?
How to convert video/audio file to byte array and vice versa in android.?
我正在尝试将 audio/video 转换为字节数组,反之亦然,
使用下面的代码可以将 audio/video 文件转换为字节数组(见下面的代码)但是我无法转换大文件(超过 50MB 的文件)是否有任何限制。?
如何将字节数组转换为 audio/video 文件。?请帮助我。
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;
}
请帮忙出结果
你创建的ByteArrayOutputStream保存在内存中。如果您处理大文件,那么您的内存会限制您的能力。这个:java.lang.OutOfMemoryError: Java heap space 问题有一个可能适合你的解决方案,尽管在内存中保留 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);
}
}
谢谢...在你的帮助下我得到了解决方案,将字节转换为文件(audio/video),见下面的代码。
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 包含路径,用它来播放你的 audio/video 文件**
我正在尝试将 audio/video 转换为字节数组,反之亦然, 使用下面的代码可以将 audio/video 文件转换为字节数组(见下面的代码)但是我无法转换大文件(超过 50MB 的文件)是否有任何限制。? 如何将字节数组转换为 audio/video 文件。?请帮助我。
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;
}
请帮忙出结果
你创建的ByteArrayOutputStream保存在内存中。如果您处理大文件,那么您的内存会限制您的能力。这个:java.lang.OutOfMemoryError: Java heap space 问题有一个可能适合你的解决方案,尽管在内存中保留 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);
}
}
谢谢...在你的帮助下我得到了解决方案,将字节转换为文件(audio/video),见下面的代码。
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 包含路径,用它来播放你的 audio/video 文件**