下面列出了怎么用android.content.res.AssetFileDescriptor的API类实例代码及写法,或者点击链接到github查看源代码。
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
null);
if (cursor.moveToFirst()) {
final String data = cursor.getString(VideoThumbnailQuery._DATA);
return new AssetFileDescriptor(ParcelFileDescriptor.open(
new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
AssetFileDescriptor.UNKNOWN_LENGTH);
}
} finally {
IoUtils.closeQuietly(cursor);
}
return null;
}
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
null);
if (cursor.moveToFirst()) {
final String data = cursor.getString(VideoThumbnailQuery._DATA);
return new AssetFileDescriptor(ParcelFileDescriptor.open(
new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
AssetFileDescriptor.UNKNOWN_LENGTH);
}
} finally {
IoUtils.closeQuietly(cursor);
}
return null;
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
public static int getDuration(MediaPlayer mediaPlayer, AssetFileDescriptor afd) {
int duration = 500;
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
mediaPlayer.prepare();
duration = mediaPlayer.getDuration();
} catch(IOException e) {
Log.e(TAG, e.toString());
}
mediaPlayer.reset();
return duration;
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
private void initMediaPlayer(SurfaceHolder holder){
mediaPlayer = new MediaPlayer();
try {
AssetManager assetMg = getApplicationContext().getAssets();
AssetFileDescriptor fileDescriptor = assetMg.openFd(此处资源asset请从鸿洋大神那获取);
mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(), fileDescriptor.getLength());
mediaPlayer.setDisplay(holder);
mediaPlayer.prepare();
mediaPlayer.setLooping(true);
mediaPlayer.setVolume(0, 0);
mediaPlayer.prepare();
}catch (Exception e){
e.printStackTrace();
}
}
private static MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// When the beep has finished playing, rewind to queue up another one.
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer player) {
player.seekTo(0);
}
});
AssetFileDescriptor file = activity.getResources().openRawResourceFd(fakeR.getId("raw", "beep"));
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
protected AssetFileDescriptor openVideoThumbnailCleared(long id, CancellationSignal signal)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(Video.Thumbnails.EXTERNAL_CONTENT_URI,
VideoThumbnailQuery.PROJECTION, Video.Thumbnails.VIDEO_ID + "=" + id, null,
null);
if (cursor.moveToFirst()) {
final String data = cursor.getString(VideoThumbnailQuery._DATA);
return new AssetFileDescriptor(ParcelFileDescriptor.open(
new File(data), ParcelFileDescriptor.MODE_READ_ONLY), 0,
AssetFileDescriptor.UNKNOWN_LENGTH);
}
} finally {
IoUtils.closeQuietly(cursor);
}
return null;
}
private void startPlaying(SurfaceTexture surfaceTexture)
{
renderer = new VideoTextureRenderer(surfaceTexture, surfaceWidth, surfaceHeight, videoTexture -> {
// This runs on background thread as well.
player = new MediaPlayer();
try
{
AssetFileDescriptor afd = getAssets().openFd("big_buck_bunny.mp4");
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
player.setSurface(new Surface(videoTexture));
player.setLooping(true);
player.prepare();
renderer.setVideoSize(player.getVideoWidth(), player.getVideoHeight());
player.start();
}
catch (IOException e)
{
throw new RuntimeException("Could not open input video!");
}
});
}
/**
* Makes a new sound pool, loads the requested sound and plays it once it's loaded
* Could be made a LOT better by reusing the same pool and checking if it's already loaded
*
* @param file the sound to play
*/
public static void playSound(String file) {
if (P.getBool("mute_sounds")) return;
SoundPool pool = buildPool();
try {
AssetFileDescriptor fd = getContext().getAssets().openFd(file);
pool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
soundPool.play(i, 1, 1, 1, 0, 1);
}
});
pool.load(fd, 1);
} catch (Exception ignored) {
//
}
}
public Boolean processAndPlayFile(String fileName)
{
try
{
setStatus(STATUS_STARTING_FILE);
player = new OBAudioBufferPlayer(true);
AssetFileDescriptor afd = OBAudioManager.audioManager.getAudioPathFD(fileName);
if (afd == null)
{
allFilesDone = true;
return false;
}
player.startPlaying(afd);
}
catch (Exception e)
{
allFilesDone = true;
return false;
}
return true;
}
private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
AssetFileDescriptor file = activity.getResources().openRawResourceFd(
R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(),
file.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer = null;
}
return mediaPlayer;
}
private boolean playMediaUrl(String mediaUrl) {
getTvPlayer();
Log.d(TAG, "Play " + mediaUrl);
try {
if (mediaUrl.startsWith("assets://")) {
AssetFileDescriptor fileDescriptor = getAssets().openFd(mediaUrl.substring(9));
mMockTvPlayer.playMediaFromAssets(fileDescriptor);
} else {
mMockTvPlayer.playMedia(mediaUrl);
}
} catch (IOException e) {
e.printStackTrace();
notifyVideoUnavailable(TvInputManager.VIDEO_UNAVAILABLE_REASON_UNKNOWN);
return false;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
notifyTimeShiftStatusChanged(TvInputManager.TIME_SHIFT_STATUS_AVAILABLE);
}
notifyVideoAvailable();
return true;
}
@Override
public void cancel() {
synchronized (recognizerLock) {
if (isRecording) {
audioRecord.stop();
isRecording = false;
final AssetFileDescriptor cancelSound = config.getRecognizerCancelSound();
if (cancelSound != null) {
playSound(cancelSound);
}
}
if (recognizeTask != null) {
recognizeTask.cancel(true);
}
onListeningCancelled();
}
}
public static FileInfo getContactAsVCardFile(Context context, Uri uri) {
AssetFileDescriptor fd;
try {
fd = context.getContentResolver().openAssetFileDescriptor(uri, "r");
java.io.FileInputStream in = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
in.read(buf);
in.close();
String vCardText = new String(buf);
Log.d("Vcard", vCardText);
List<String> pathSegments = uri.getPathSegments();
String targetPath = "/" + pathSegments.get(pathSegments.size() - 1) + ".vcf";
SecureMediaStore.copyToVfs(buf, targetPath);
FileInfo info = new FileInfo();
info.stream = new info.guardianproject.iocipher.FileInputStream(SecureMediaStore.vfsUri(targetPath).getPath());
info.type = "text/vcard";
return info;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static SoundFile create(long audioId, String dataColumn,
ProgressListener progressListener)
throws java.io.FileNotFoundException,
java.io.IOException, InvalidInputException {
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, String.valueOf(audioId));
AssetFileDescriptor file;
// will throw FileNotFoundException if file does not exist
file = App.getInstance().getContentResolver().openAssetFileDescriptor(uri, "r");
String name = dataColumn.toLowerCase();
String[] components = name.split("\\.");
if (components.length < 2) {
return null;
}
if (!Arrays.asList(getSupportedExtensions()).contains(components[components.length - 1])) {
return null;
}
SoundFile soundFile = new SoundFile();
soundFile.setProgressListener(progressListener);
soundFile.ParseFile(uri, file, dataColumn);
return soundFile;
}
/**
* create mediaplayer for music
*
* @param pPath
* the pPath relative to assets
* @return
*/
private MediaPlayer createMediaplayer(final String pPath) {
MediaPlayer mediaPlayer = new MediaPlayer();
try {
if (pPath.startsWith("/")) {
final FileInputStream fis = new FileInputStream(pPath);
mediaPlayer.setDataSource(fis.getFD());
fis.close();
} else {
final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(pPath);
mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
mediaPlayer.prepare();
mediaPlayer.setVolume(this.mLeftVolume, this.mRightVolume);
} catch (final Exception e) {
mediaPlayer = null;
Log.e(Cocos2dxMusic.TAG, "error: " + e.getMessage(), e);
}
return mediaPlayer;
}
public void loadVideoPlayer()
{
OBControl videoBox = objectDict.get("video_box");
String videoFilePath = getLocalPath(String.format("%s.mp4",videoName));
videoPlayer = new OBVideoPlayer(videoBox.frame(), this, false, false);
AssetFileDescriptor afd = OBUtils.getAssetFileDescriptorForPath(videoFilePath);
videoPlayer.prepareForPlaying(afd,0,null);
videoPlayer.playAfterPrepare = false;
videoPlayer.stopOnCompletion = false;
videoBox.hide();
videoPlayer.hide();
attachControl(videoPlayer);
OBPath path = (OBPath)objectDict.get("video_frame");
path.sizeToBoundingBoxIncludingStroke();
path.setZPosition(9);
videoPlayer.setZPosition(10);
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
/**
* Opens a stream to the given URI.
* @return Never returns null.
* @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be
* resolved before being passed into this function.
* @throws Throws an IOException if the URI cannot be opened.
*/
public OutputStream openOutputStream(Uri uri, boolean append) throws IOException {
assertBackgroundThread();
switch (getUriType(uri)) {
case URI_TYPE_FILE: {
File localFile = new File(uri.getPath());
File parent = localFile.getParentFile();
if (parent != null) {
parent.mkdirs();
}
return new FileOutputStream(localFile, append);
}
case URI_TYPE_CONTENT:
case URI_TYPE_RESOURCE: {
AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, append ? "wa" : "w");
return assetFd.createOutputStream();
}
}
throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
}
public void startPlaying (String fileName, String channel)
{
OBGeneralAudioPlayer player = playerForChannel(channel);
if (fileName == null)
player.stopPlaying();
else
{
AssetFileDescriptor fd = getAudioPathFD(fileName);
if (fd != null)
{
player.startPlaying(fd);
}
else
{
MainActivity.log("Error caught in OBAudioManager.startPlaying [" + fileName + "] returned a null file descriptor");
}
}
}
private MediaPlayer buildMediaPlayer(Context activity) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
try {
AssetFileDescriptor file = activity.getResources().openRawResourceFd(R.raw.beep);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
} finally {
file.close();
}
mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
mediaPlayer.prepare();
return mediaPlayer;
} catch (IOException ioe) {
Log.w(TAG, ioe);
mediaPlayer.release();
return null;
}
}
private static boolean isFileExistsApi29(String filePath) {
if (Build.VERSION.SDK_INT >= 29) {
try {
Uri uri = Uri.parse(filePath);
ContentResolver cr = Utils.getApp().getContentResolver();
AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r");
if (afd == null) return false;
try {
afd.close();
} catch (IOException ignore) {
}
} catch (FileNotFoundException e) {
return false;
}
return true;
}
return false;
}
/**
* Check whether a content URI exists.
*
* @param uriString the content URI to query.
* @return true if the URI exists, or false otherwise.
*/
@CalledByNative
public static boolean contentUriExists(String uriString) {
AssetFileDescriptor asf = null;
try {
asf = getAssetFileDescriptor(uriString);
return asf != null;
} finally {
// Do not use StreamUtil.closeQuietly here, as AssetFileDescriptor
// does not implement Closeable until KitKat.
if (asf != null) {
try {
asf.close();
} catch (IOException e) {
// Closing quietly.
}
}
}
}
public void changeBGM(final int newBGM, final int... pos) {
BGMFader.stop(bgm, 400, new Runnable() {
@Override
public void run() {
bgm.reset();
bgmId = newBGM;
AssetFileDescriptor afd = GameActivity.getInstance().getResources().
openRawResourceFd(bgmId);
if (afd == null) return;
try {
bgm.setDataSource(
afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
bgm.prepare();
} catch (IOException | IllegalStateException e) {
e.printStackTrace();
}
bgm.setLooping(true);
if (pos.length > 0) { bgm.seekTo(pos[0]); }
}
});
}
public void playJingle(int jingleId) {
jingle.reset();
bgm.setVolume(0, 0);
AssetFileDescriptor afd = GameActivity.getInstance().getResources().
openRawResourceFd(jingleId);
if (afd == null) return;
try {
jingle.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
jingle.prepare();
} catch (IOException e) {
e.printStackTrace();
}
jingle.start();
jingle.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
bgm.setVolume(1, 1);
}
});
}
/**
* Creates drawable from AssetFileDescriptor.
* Convenience wrapper for {@link GifDrawable#GifDrawable(FileDescriptor)}
*
* @param afd source
* @throws NullPointerException if afd is null
* @throws IOException when opening failed
*/
public GifDrawable(AssetFileDescriptor afd) throws IOException {
if (afd == null)
throw new NullPointerException("Source is null");
FileDescriptor fd = afd.getFileDescriptor();
try {
mGifInfoPtr = openFd(mMetaData, fd, afd.getStartOffset(), false);
} catch (IOException ex) {
afd.close();
throw ex;
}
mColors = new int[mMetaData[0] * mMetaData[1]];
mInputSourceLength = afd.getLength();
}
public OpenForReadResult(Uri uri, InputStream inputStream, String mimeType, long length, AssetFileDescriptor assetFd) {
this.uri = uri;
this.inputStream = inputStream;
this.mimeType = mimeType;
this.length = length;
this.assetFd = assetFd;
}