阅读资源声音文件转换成字节数组 [英] Reading a resource sound file into a Byte array

查看:145
本文介绍了阅读资源声音文件转换成字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 cheerapp.wav cheerapp.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();          

对于音乐字节数组,从的DataInputStream 取数据。我不知道什么是长度来分配。

For the music byte array which takes the data from the DataInputStream. I don't know what the length of that to allocate.

这是从资源的原始文件不是一个文件,所以我不知道那个东西的尺寸。

This is raw file from resource not a file therefore I wouldn't know the size of that thing.

推荐答案

您确实有字节数组的长度,你可以看到:

You do have byte array length as you can see:

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

然后你就可以读全码流为字节数组容易。

And then you can read whole Stream into byte array easily.

当然,我会建议你做检查,当涉及到的规模和应使用ByteArrayOutputStream较小byte []的缓冲区,如果需要的:

Of course I would recommend that you do check when it comes to the size and use ByteArrayOutputStream with smaller byte[] buffer if needed:

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到你的项目,你就只是做:

If you'll be doing lots of IO operations I recommend that you make use of org.apache.commons.io.IOUtils. That way you won't need to worry too much about quality of your IO implementation and once you import JAR into your project you would just do:

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

这篇关于阅读资源声音文件转换成字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆