【问题标题】:Reading a resource sound file into a Byte array将资源声音文件读入字节数组
【发布时间】:2013-02-26 20:29:22
【问题描述】:

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

对于从DataInputStream 获取数据的music 字节数组。我不知道要分配多少长度。

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

【问题讨论】:

标签: android android-resources


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    希望它会有所帮助。

    创建一个sdcard路径:

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

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多