我发现了一种相当简单的方法来从MMS读取视频/音频数据,因此我决定发布我的课程的这一部分,为所有需要此功能的用户提供MMS附件。
private static final int RAW_DATA_BLOCK_SIZE = 16384; //Set the block size used to write a ByteArrayOutputStream to byte[]
public static final int ERROR_IO_EXCEPTION = 1;
public static final int ERROR_FILE_NOT_FOUND = 2;
public static byte[] LoadRaw(Context context, Uri uri, int Error){
InputStream inputStream = null;
byte[] ret = new byte[0];
//Open inputStream from the specified URI
try {
inputStream = context.getContentResolver().openInputStream(uri);
//Try read from the InputStream
if(inputStream!=null)
ret = InputStreamToByteArray(inputStream);
}
catch (FileNotFoundException e1) {
Error = ERROR_FILE_NOT_FOUND;
}
catch (IOException e) {
Error = ERROR_IO_EXCEPTION;
}
finally{
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
//Problem on closing stream.
//The return state does not change.
Error = ERROR_IO_EXCEPTION;
}
}
}
//Return
return ret;
}
//Create a byte array from an open inputStream. Read blocks of RAW_DATA_BLOCK_SIZE byte
private static byte[] InputStreamToByteArray(InputStream inputStream) throws IOException{
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[RAW_DATA_BLOCK_SIZE];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
通过这种方式,你可以提取“原始”数据,如音频/视频的传递从MMS /图片:
- ,你需要使用此功能
- 的URI上下文包含要提取的数据的MMS部分(例如“content:// mms/part/2”)
- byref参数返回过程抛出的最终错误代码。
一旦你有了你的byte [],你可以创建一个空文件,然后使用FileOutputStream将byte []写入它。如果文件路径\扩展名正确,并且您的应用具有所有权限 权限,则可以存储您的数据。
PS。这个过程已经过几次测试,并且工作正常,但是我不排除可能是一些可能产生错误状态的非托管异常情况。恕我直言,它也可以被改进...
感谢此代码段!它真的帮了我很多。访问MMS附件的代码示例很难找到! – jenzz 2012-09-08 22:25:13
感谢它为我工作。 :) – 2015-05-13 11:44:35