jas*_*ite 6 android android-resources
我有cheerapp.wav或cheerapp.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();
Run Code Online (Sandbox Code Playgroud)
对于music从中获取数据的字节数组DataInputStream.我不知道分配的长度是多少.
这是资源而不是文件的原始文件,因此我不知道那个东西的大小.
nik*_*3ro 18
您可以看到字节数组长度:
InputStream inStream = context.getResources().openRawResource(R.raw.cheerapp);
byte[] music = new byte[inStream.available()];
Run Code Online (Sandbox Code Playgroud)
然后您可以轻松地将整个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
}
Run Code Online (Sandbox Code Playgroud)
如果你要做很多IO操作,我建议你使用org.apache.commons.io.IOUtils.这样你就不必太担心IO实现的质量了,一旦你将JAR导入你的项目,你就会这样做:
byte[] payload = IOUtils.toByteArray(context.getResources().openRawResource(R.raw.cheerapp));
Run Code Online (Sandbox Code Playgroud)
希望它会有所帮助。
创建SD卡路径:
String outputFile =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
Run Code Online (Sandbox Code Playgroud)
转换为文件并必须调用字节数组方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20115 次 |
| 最近记录: |