gpt4 book ai didi

android - 将资源声音文件读入字节数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:22:23 26 4
gpt4 key购买 nike

我有 cheerapp.wavcheerapp.mp3 或其他格式。

InputStream in = context.getResources().openRawResource(R.raw.cheerapp);       
BufferedInputStream bis = new BufferedInputStream(in, 8000);
// Create a DataInputStream to read the audio data from the saved file
DataInputStream dis = new DataInputStream(bis);

byte[] music = null;
music = new byte[??];
int i = 0; // Read the file into the "music" array
while (dis.available() > 0) {
// dis.read(music[i]); // This assignment does not reverse the order
music[i]=dis.readByte();
i++;
}

dis.close();

对于 music 字节数组,它从 DataInputStream 中获取数据。我不知道要分配的长度是多少。

这是来自资源的原始文件而不是文件,因此我不知道那个东西的大小。

最佳答案

如您所见,您确实有字节数组长度:

 InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];

然后您可以轻松地将整个 Stream 读入字节数组。

当然,我会建议您检查大小并在需要时使用具有较小 byte[] 缓冲区的 ByteArrayOutputStream:

public static byte[] convertStreamToByteArray(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[10240];
int i = Integer.MAX_VALUE;
while ((i = is.read(buff, 0, buff.length)) > 0) {
baos.write(buff, 0, i);
}

return baos.toByteArray(); // be sure to close InputStream in calling function
}

如果您要进行大量 IO 操作,我建议您使用 org.apache.commons.io.IOUtils .这样你就不必太担心 IO 实现的质量,一旦你将 JAR 导入到你的项目中,你只需要做:

byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));

关于android - 将资源声音文件读入字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com