Reading a resource sound file into a Byte array

て烟熏妆下的殇ゞ 提交于 2019-11-29 02:26:02

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

Hope it will help.

Create an sdcard path:

String outputFile = 
    Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";

Convert as a file and have to call the byte array method:

byte[] soundBytes;

try {
    InputStream inputStream = 
        getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));

    soundBytes = new byte[inputStream.available()];
    soundBytes = toByteArray(inputStream);

    Toast.makeText(this, "Recordin Finished"+ " " + soundBytes, Toast.LENGTH_LONG).show();
} catch(Exception e) {
    e.printStackTrace();
}

method:

public byte[] toByteArray(InputStream in) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int read = 0;
    byte[] buffer = new byte[1024];
    while (read != -1) {
        read = in.read(buffer);
        if (read != -1)
            out.write(buffer,0,read);
    }
    out.close();
    return out.toByteArray();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!