2013-02-26 58 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(); 
}