Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

android - Reading a resource sound file into a Byte array

I have cheerapp.wav or cheerapp.mp3 or some other format.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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
}

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...