7

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

对于musicDataInputStream. 我不知道要分配的长度。

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

4

2 回答 2

20

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

 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));
于 2013-02-26T20:42:58.590 回答
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();
}
于 2016-09-26T09:45:16.840 回答