2013-02-26 34 views
4

我有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的数据。我不知道分配的时间长短。

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

+0

考虑使用[Apache的百科全书] (http://commons.apache.org/proper/commons-io/)。 – JJD 2013-10-08 14:38:54

回答

13

你确实有字节数组的长度,你可以看到:

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

然后你就可以轻松地阅读整流成字节数组。

当然,我会建议你做检查,当涉及到大小,并用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)); 
3

希望这将有助于。

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