将资源声音文件读入Byte数组

时间:2013-02-26 20:29:22

标签: android android-resources

我有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字节数组。我不知道分配的长度是多少。

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

2 个答案:

答案 0 :(得分:18)

您可以看到字节数组长度:

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

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

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

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

答案 1 :(得分:4)

希望它会有所帮助。

创建SD卡路径:

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

转换为文件并且必须调用字节数组方法:

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

方法:

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