為了防止系統(tǒng)或其他軟件播放app內(nèi)部的緩存視頻,需要對緩存的視頻進行加密和解密操作
1.對緩存視頻進行加密,緩存使用AndroidVideoCache方案
FileCache.java文件進行加密操作,比較簡單的數(shù)據(jù)反向
public class FileCache implements Cache {
public static final int ENCRYPT_SIZE = 32;
@Override
public synchronized void complete() throws ProxyCacheException {
if (isCompleted()) {
return;
}
//--------------------------加密開始--------------------------//
try {
dataFile.seek(0);
byte[] oldByte = new byte[ENCRYPT_SIZE];
byte[] newByte = new byte[ENCRYPT_SIZE];
if (dataFile.read(oldByte) >= ENCRYPT_SIZE) {
for (int i = 0; i < oldByte.length; i++) {
newByte[oldByte.length - 1 - i] = oldByte[i];
}
dataFile.seek(0);
dataFile.write(newByte);
//--------------------------加密結(jié)束--------------------------//
}
} catch (IOException e) {
e.printStackTrace();
}
close();
......
}
2.讀取緩存,解碼,需要實現(xiàn)ijk的IMediaDataSource
public class FileMediaDataSource implements IMediaDataSource {
private RandomAccessFile mFile;
private long mFileSize;
public FileMediaDataSource(File file) throws IOException {
mFile = new RandomAccessFile(file, "r");
mFileSize = mFile.length();
}
@Override
public int readAt(long position, byte[] buffer, int offset, int size) throws IOException {
if (mFile.getFilePointer() != position) {
mFile.seek(position);
}
if (size == 0) {
return 0;
}
int read = mFile.read(buffer, 0, size);
//--------------------------解密開始--------------------------//
byte[] bufferHead = new byte[FileCache.ENCRYPT_SIZE];
if (read >= bufferHead.length && position == 0) {
//加密算法為前面一小段反向
System.arraycopy(buffer, 0, bufferHead, 0, bufferHead.length);
for (int i = 0; i < bufferHead.length; i++) {
buffer[bufferHead.length - 1 - i] = bufferHead[i];
}
}
//--------------------------解密結(jié)束--------------------------//
return read;
}
@Override
public long getSize() throws IOException {
return mFileSize;
}
@Override
public void close() throws IOException {
mFileSize = 0;
mFile.close();
mFile = null;
}
}
3.設置播放的DataSource
HttpProxyCacheServer mCacheServer ;//自己設置AndroidVideoCache代理
IjkMediaPlayer ijkPlayer;//ijk的播放器
if (mCacheServer.isCached(mUrl)) {
File file = mCacheServer.getCacheFile(mUrl);//默認是private的,自己處理下
try {
ijkPlayer.setDataSource(new FileMediaDataSource (file));
} catch (IOException e) {
e.printStackTrace();
mMediaPlayer.setDataSource(proxyPath, mHeaders);
}
}