Search in sources :

Example 26 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project platform_frameworks_base by android.

the class SoundPool method load.

/**
     * Load the sound from the specified APK resource.
     *
     * Note that the extension is dropped. For example, if you want to load
     * a sound from the raw resource file "explosion.mp3", you would specify
     * "R.raw.explosion" as the resource ID. Note that this means you cannot
     * have both an "explosion.wav" and an "explosion.mp3" in the res/raw
     * directory.
     * 
     * @param context the application context
     * @param resId the resource ID
     * @param priority the priority of the sound. Currently has no effect. Use
     *                 a value of 1 for future compatibility.
     * @return a sound ID. This value can be used to play or unload the sound.
     */
public int load(Context context, int resId, int priority) {
    AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
    int id = 0;
    if (afd != null) {
        id = _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority);
        try {
            afd.close();
        } catch (java.io.IOException ex) {
        //Log.d(TAG, "close failed:", ex);
        }
    }
    return id;
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor)

Example 27 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project platform_frameworks_base by android.

the class SimplePlayer method playOrPause.

public void playOrPause() {
    if (mMediaPlayer == null || !mMediaPlayer.isPlaying()) {
        if (mMediaPlayer == null) {
            try {
                mMediaPlayer = new MediaPlayer();
                if (mSession != 0) {
                    mMediaPlayer.setAudioSessionId(mSession);
                    Log.d(TAG, "mMediaPlayer.setAudioSessionId(): " + mSession);
                }
                if (mFileName.equals("")) {
                    Log.d(TAG, "Playing from resource");
                    AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(mFileResId);
                    mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                    afd.close();
                } else {
                    Log.d(TAG, "Playing file: " + mFileName);
                    mMediaPlayer.setDataSource(mFileName);
                }
                mMediaPlayer.setAudioStreamType(mStreamType);
                mMediaPlayer.prepare();
                mMediaPlayer.setLooping(true);
            } catch (IOException ex) {
                Log.e(TAG, "mMediaPlayercreate failed:", ex);
                mMediaPlayer = null;
            } catch (IllegalArgumentException ex) {
                Log.e(TAG, "mMediaPlayercreate failed:", ex);
                mMediaPlayer = null;
            } catch (SecurityException ex) {
                Log.e(TAG, "mMediaPlayercreate failed:", ex);
                mMediaPlayer = null;
            }
            if (mMediaPlayer != null) {
                mMediaPlayer.setAuxEffectSendLevel(mSendLevel);
                mMediaPlayer.attachAuxEffect(mEffectId);
                mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                    public void onCompletion(MediaPlayer mp) {
                        updatePlayPauseButton();
                    }
                });
                mSessionText.setText("Session: " + Integer.toString(mMediaPlayer.getAudioSessionId()));
            }
        }
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
        }
    } else {
        mMediaPlayer.pause();
    }
    updatePlayPauseButton();
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) IOException(java.io.IOException) MediaPlayer(android.media.MediaPlayer)

Example 28 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project platform_frameworks_base by android.

the class CopyJob method copyFileHelper.

/**
     * Handles copying a single file.
     *
     * @param src Info of the file to copy from.
     * @param dest Info of the *file* to copy to. Must be created beforehand.
     * @param destParent Info of the parent of the destination.
     * @param mimeType Mime type for the target. Can be different than source for virtual files.
     * @throws ResourceException
     */
private void copyFileHelper(DocumentInfo src, DocumentInfo dest, DocumentInfo destParent, String mimeType) throws ResourceException {
    CancellationSignal canceller = new CancellationSignal();
    AssetFileDescriptor srcFileAsAsset = null;
    ParcelFileDescriptor srcFile = null;
    ParcelFileDescriptor dstFile = null;
    InputStream in = null;
    ParcelFileDescriptor.AutoCloseOutputStream out = null;
    boolean success = false;
    try {
        // as such format.
        if (src.isVirtualDocument()) {
            try {
                srcFileAsAsset = getClient(src).openTypedAssetFileDescriptor(src.derivedUri, mimeType, null, canceller);
            } catch (FileNotFoundException | RemoteException | RuntimeException e) {
                throw new ResourceException("Failed to open a file as asset for %s due to an " + "exception.", src.derivedUri, e);
            }
            srcFile = srcFileAsAsset.getParcelFileDescriptor();
            try {
                in = new AssetFileDescriptor.AutoCloseInputStream(srcFileAsAsset);
            } catch (IOException e) {
                throw new ResourceException("Failed to open a file input stream for %s due " + "an exception.", src.derivedUri, e);
            }
        } else {
            try {
                srcFile = getClient(src).openFile(src.derivedUri, "r", canceller);
            } catch (FileNotFoundException | RemoteException | RuntimeException e) {
                throw new ResourceException("Failed to open a file for %s due to an exception.", src.derivedUri, e);
            }
            in = new ParcelFileDescriptor.AutoCloseInputStream(srcFile);
        }
        try {
            dstFile = getClient(dest).openFile(dest.derivedUri, "w", canceller);
        } catch (FileNotFoundException | RemoteException | RuntimeException e) {
            throw new ResourceException("Failed to open the destination file %s for writing " + "due to an exception.", dest.derivedUri, e);
        }
        out = new ParcelFileDescriptor.AutoCloseOutputStream(dstFile);
        byte[] buffer = new byte[32 * 1024];
        int len;
        try {
            while ((len = in.read(buffer)) != -1) {
                if (isCanceled()) {
                    if (DEBUG)
                        Log.d(TAG, "Canceled copy mid-copy of: " + src.derivedUri);
                    return;
                }
                out.write(buffer, 0, len);
                makeCopyProgress(len);
            }
            // Need to invoke IoUtils.close explicitly to avoid from ignoring errors at flush.
            IoUtils.close(dstFile.getFileDescriptor());
            srcFile.checkError();
        } catch (IOException e) {
            throw new ResourceException("Failed to copy bytes from %s to %s due to an IO exception.", src.derivedUri, dest.derivedUri, e);
        }
        if (src.isVirtualDocument()) {
            convertedFiles.add(src);
        }
        success = true;
    } finally {
        if (!success) {
            if (dstFile != null) {
                try {
                    dstFile.closeWithError("Error copying bytes.");
                } catch (IOException closeError) {
                    Log.w(TAG, "Error closing destination.", closeError);
                }
            }
            if (DEBUG)
                Log.d(TAG, "Cleaning up failed operation leftovers.");
            canceller.cancel();
            try {
                deleteDocument(dest, destParent);
            } catch (ResourceException e) {
                Log.w(TAG, "Failed to cleanup after copy error: " + src.derivedUri, e);
            }
        }
        // This also ensures the file descriptors are closed.
        IoUtils.closeQuietly(in);
        IoUtils.closeQuietly(out);
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ParcelFileDescriptor(android.os.ParcelFileDescriptor) RemoteException(android.os.RemoteException) CancellationSignal(android.os.CancellationSignal)

Example 29 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project platform_frameworks_base by android.

the class ContentProviderProxy method openAssetFile.

@Override
public AssetFileDescriptor openAssetFile(String callingPkg, Uri url, String mode, ICancellationSignal signal) throws RemoteException, FileNotFoundException {
    Parcel data = Parcel.obtain();
    Parcel reply = Parcel.obtain();
    try {
        data.writeInterfaceToken(IContentProvider.descriptor);
        data.writeString(callingPkg);
        url.writeToParcel(data, 0);
        data.writeString(mode);
        data.writeStrongBinder(signal != null ? signal.asBinder() : null);
        mRemote.transact(IContentProvider.OPEN_ASSET_FILE_TRANSACTION, data, reply, 0);
        DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(reply);
        int has = reply.readInt();
        AssetFileDescriptor fd = has != 0 ? AssetFileDescriptor.CREATOR.createFromParcel(reply) : null;
        return fd;
    } finally {
        data.recycle();
        reply.recycle();
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) Parcel(android.os.Parcel)

Example 30 with AssetFileDescriptor

use of android.content.res.AssetFileDescriptor in project platform_frameworks_base by android.

the class TestDocumentsProvider method openDocumentThumbnail.

@Override
public AssetFileDescriptor openDocumentThumbnail(String docId, Point sizeHint, CancellationSignal signal) throws FileNotFoundException {
    if (LAG)
        lagUntilCanceled(signal);
    if (THUMB_WEDGE)
        wedgeUntilCanceled(signal);
    if (THUMB_CRASH)
        System.exit(12);
    final Bitmap bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(bitmap);
    final Paint paint = new Paint();
    paint.setColor(Color.BLUE);
    canvas.drawColor(Color.RED);
    canvas.drawLine(0, 0, 32, 32, paint);
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 50, bos);
    final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    try {
        final ParcelFileDescriptor[] fds = ParcelFileDescriptor.createReliablePipe();
        new AsyncTask<Object, Object, Object>() {

            @Override
            protected Object doInBackground(Object... params) {
                final FileOutputStream fos = new FileOutputStream(fds[1].getFileDescriptor());
                try {
                    Streams.copy(bis, fos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                IoUtils.closeQuietly(fds[1]);
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return new AssetFileDescriptor(fds[0], 0, AssetFileDescriptor.UNKNOWN_LENGTH);
    } catch (IOException e) {
        throw new FileNotFoundException(e.getMessage());
    }
}
Also used : AssetFileDescriptor(android.content.res.AssetFileDescriptor) Canvas(android.graphics.Canvas) FileNotFoundException(java.io.FileNotFoundException) Paint(android.graphics.Paint) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Bitmap(android.graphics.Bitmap) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) ParcelFileDescriptor(android.os.ParcelFileDescriptor)

Aggregations

AssetFileDescriptor (android.content.res.AssetFileDescriptor)187 IOException (java.io.IOException)98 ParcelFileDescriptor (android.os.ParcelFileDescriptor)49 FileNotFoundException (java.io.FileNotFoundException)41 Test (org.junit.Test)28 MediaPlayer (android.media.MediaPlayer)27 ContentResolver (android.content.ContentResolver)26 RemoteException (android.os.RemoteException)19 File (java.io.File)18 FileInputStream (java.io.FileInputStream)16 Nullable (android.annotation.Nullable)15 Parcel (android.os.Parcel)14 Bitmap (android.graphics.Bitmap)13 FileDescriptor (java.io.FileDescriptor)13 DeadObjectException (android.os.DeadObjectException)12 Resources (android.content.res.Resources)11 FileOutputStream (java.io.FileOutputStream)11 InputStream (java.io.InputStream)11 Uri (android.net.Uri)10 Bundle (android.os.Bundle)10