@Override protected Drawable doInBackground(Integer... params) { AssetFileDescriptor fd = null; InputStream is = null; BitmapFactory.Options opts; rawContactId = params[0]; BitmapDrawable result = null; Uri rawContactPhotoUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); try { // Get the bounds for later resampling fd = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "r"); is = fd.createInputStream(); opts = new Options(); opts.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, opts); is.close(); fd.close(); opts.inSampleSize = opts.outHeight / thumbSize; opts.inSampleSize = opts.inSampleSize < 1 ? 1 : opts.inSampleSize; opts.inJustDecodeBounds = false; fd = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "r"); is = fd.createInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(is, null, opts); if (bitmap == null) return unchangedThumb; result = new BitmapDrawable(getResources(), bitmap); return result; } catch (FileNotFoundException e) { return null; } catch (IOException e) { return null; } finally { if (is != null) try { is.close(); } catch (IOException e) { } if (fd != null) try { fd.close(); } catch (IOException e) { } } }
GifInfoHandle(AssetFileDescriptor afd, boolean justDecodeMetaData) throws IOException { try { gifInfoPtr = openFd(afd.getFileDescriptor(), afd.getStartOffset(), justDecodeMetaData); } finally { afd.close(); } }
public static MediaPlayer create(Context context, int resid) { try { AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid); if (afd == null) return null; MediaPlayer mp = new MediaPlayer(); mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mp.prepare(); return mp; } catch (IOException ex) { Log.d(TAG, "create failed:", ex); // fall through } catch (IllegalArgumentException ex) { Log.d(TAG, "create failed:", ex); // fall through } catch (SecurityException ex) { Log.d(TAG, "create failed:", ex); // fall through } catch (Exception ex) { Log.d(TAG, "create failed:", ex); // fall through } return null; }
private static boolean hasCodecsForResourceCombo( Context context, int resourceId, int track, String mimePrefix) { try { AssetFileDescriptor afd = null; MediaExtractor ex = null; try { afd = context.getResources().openRawResourceFd(resourceId); ex = new MediaExtractor(); ex.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); if (mimePrefix != null) { return hasCodecForMediaAndDomain(ex, mimePrefix); } else if (track == ALL_AV_TRACKS) { return hasCodecsForMedia(ex); } else { return hasCodecForTrack(ex, track); } } finally { if (ex != null) { ex.release(); } if (afd != null) { afd.close(); } } } catch (IOException e) { Log.i(TAG, "could not open resource"); } return false; }
/** * Decodes and scales a contact's image from a file pointed to by a Uri in the contact's data, and * returns the result as a Bitmap. The column that contains the Uri varies according to the * platform version. * * @param photoData provide the Contact.PHOTO_THUMBNAIL_URI value. * @param imageSize The desired target width and height of the output image in pixels. * @return A Bitmap containing the contact's image, resized to fit the provided image size. If no * thumbnail exists, returns null. */ private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) { // Ensures the Fragment is still added to an activity. As this method is called in a // background thread, there's the possibility the Fragment is no longer attached and // added to an activity. If so, no need to spend resources loading the contact photo. if (!isAdded() || getActivity() == null) { return null; } // Instantiates an AssetFileDescriptor. Given a content Uri pointing to an image file, the // ContentResolver // can return an AssetFileDescriptor for the file. AssetFileDescriptor afd = null; // This "try" block catches an Exception if the file descriptor returned from the Contacts // Provider doesn't point to an existing file. try { Uri thumbUri; // Converts the Uri passed as a string to a Uri object. thumbUri = Uri.parse(photoData); // Retrieves a file descriptor from the Contacts Provider. To learn more about this // feature, read the reference documentation for // ContentResolver#openAssetFileDescriptor. afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r"); // Gets a FileDescriptor from the AssetFileDescriptor. A BitmapFactory object can // decode the contents of a file pointed to by a FileDescriptor into a Bitmap. FileDescriptor fileDescriptor = afd.getFileDescriptor(); if (fileDescriptor != null) { // Decodes a Bitmap from the image pointed to by the FileDescriptor, and scales it // to the specified width and height return ImageLoader.decodeSampledBitmapFromDescriptor(fileDescriptor, imageSize, imageSize); } } catch (FileNotFoundException e) { // If the file pointed to by the thumbnail URI doesn't exist, or the file can't be // opened in "read" mode, ContentResolver.openAssetFileDescriptor throws a // FileNotFoundException. if (BuildConfig.DEBUG) { Log.d( TAG, "Contact photo thumbnail not found for contact " + photoData + ": " + e.toString()); } } finally { // If an AssetFileDescriptor was returned, try to close it if (afd != null) { try { afd.close(); } catch (IOException e) { // Closing a file descriptor might cause an IOException if the file is // already closed. Nothing extra is needed to handle this. } } } // If the decoding failed, returns null return null; }
private void setDataSourceFromResource(Resources resources, MediaPlayer player, int res) throws java.io.IOException { AssetFileDescriptor afd = resources.openRawResourceFd(res); if (afd != null) { player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } }
private void closeFD() { if (mFD != null) { try { mFD.close(); } catch (IOException e) { Log.e("closeFD", e); } mFD = null; } }
private void openVideo() { if (mUri == null || mSurfaceHolder == null) { // not ready for playback just yet, will try again later return; } // Tell the music playback service to pause // TODO: these constants need to be published somewhere in the framework. Intent i = new Intent("com.android.music.musicservicecommand"); i.putExtra("command", "pause"); getContext().sendBroadcast(i); if (mMediaPlayer != null) { mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setOnPreparedListener(mPreparedListener); mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener); mIsPrepared = false; Log.v(TAG, "reset duration to -1 in openVideo"); mDuration = -1; mMediaPlayer.setOnCompletionListener(mCompletionListener); mMediaPlayer.setOnErrorListener(mErrorListener); mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener); mCurrentBufferPercentage = 0; if (URLUtil.isAssetUrl(mUri.toString())) { // DST: 20090606 detect asset url AssetFileDescriptor afd = null; try { String path = mUri.toString().substring("file:///android_asset/".length()); afd = getContext().getAssets().openFd(path); mMediaPlayer.setDataSource( afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } finally { if (afd != null) { afd.close(); } } } else { setDataSource(); } mMediaPlayer.setDisplay(mSurfaceHolder); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setScreenOnWhilePlaying(true); mMediaPlayer.prepareAsync(); attachMediaController(); } catch (IOException ex) { Log.w(TAG, "Unable to open content: " + mUri, ex); return; } catch (IllegalArgumentException ex) { Log.w(TAG, "Unable to open content: " + mUri, ex); return; } }
public synchronized long BackgroundMusicCreateFromFile(String fileName, int[] error) { if (fileName.equals("")) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } AssetFileDescriptor fd = null; if (fileName.startsWith("/")) { File file = new File(fileName); if (!file.isFile()) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } } else { if (patchFile_ != null) fd = patchFile_.getAssetFileDescriptor(fileName); if (fd == null && mainFile_ != null) fd = mainFile_.getAssetFileDescriptor(fileName); if (fd == null) try { fd = WeakActivityHolder.get().getAssets().openFd("assets/" + fileName); } catch (IOException e) { } if (fd == null) { error[0] = GAUDIO_CANNOT_OPEN_FILE; return 0; } } MediaPlayer player = new MediaPlayer(); int duration = 0; try { if (fd != null) { player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); fd.close(); } else { player.setDataSource(fileName); } player.prepare(); duration = player.getDuration(); player.release(); player = null; } catch (Exception e) { error[0] = GAUDIO_UNRECOGNIZED_FORMAT; return 0; } long gid = nextgid(); sounds_.put(gid, new Sound(fileName, duration)); return gid; }
public synchronized long BackgroundMusicPlay(long backgroundMusic, boolean paused, long data) { Sound sound2 = sounds_.get(backgroundMusic); if (sound2 == null) return 0; String fileName = sound2.fileName; AssetFileDescriptor fd = null; if (fileName.startsWith("/")) { File file = new File(fileName); if (!file.isFile()) return 0; } else { if (patchFile_ != null) fd = patchFile_.getAssetFileDescriptor(fileName); if (fd == null && mainFile_ != null) fd = mainFile_.getAssetFileDescriptor(fileName); if (fd == null) try { fd = WeakActivityHolder.get().getAssets().openFd("assets/" + fileName); } catch (IOException e) { } if (fd == null) return 0; } MediaPlayer player = new MediaPlayer(); try { if (fd != null) { player.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); fd.close(); } else { player.setDataSource(fileName); } player.prepare(); } catch (Exception e) { return 0; } long gid = nextgid(); player.setOnCompletionListener(new OnCompletionListener(this, gid)); Channel channel = new Channel(gid, player, sound2, data); sound2.channels.add(channel); channels_.put(gid, channel); channel.paused = paused; if (!paused) channel.player.start(); return gid; }
/** Prepares given media asset (path from assets directory) for playback. */ public void prepare(final String asset) { reset(); try { AssetFileDescriptor fd = GUI.getInstance().getContext().getResources().getAssets().openFd(asset); setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength()); fd.close(); prepare(); } catch (Exception e) { e.printStackTrace(); } }
private long sizeInternal() { try { AssetFileDescriptor descriptor = myApplication.getAssets().openFd(getPath()); // for some files (archives, crt) descriptor cannot be opened if (descriptor == null) { return sizeSlow(); } long length = descriptor.getLength(); descriptor.close(); return length; } catch (IOException e) { return sizeSlow(); } }
protected void initialize() throws IOException { try { mp = new MediaPlayer(); String url = TiConvert.toString(proxy.getProperty(TiC.PROPERTY_URL)); if (URLUtil.isAssetUrl(url)) { Context context = proxy.getTiContext().getTiApp(); String path = url.substring(TiConvert.ASSET_URL.length()); AssetFileDescriptor afd = null; try { afd = context.getAssets().openFd(path); // Why mp.setDataSource(afd) doesn't work is a problem for another day. // http://groups.google.com/group/android-developers/browse_thread/thread/225c4c150be92416 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } catch (IOException e) { Log.e(LCAT, "Error setting file descriptor: ", e); } finally { if (afd != null) { afd.close(); } } } else { Uri uri = Uri.parse(url); if (uri.getScheme().equals(TiC.PROPERTY_FILE)) { mp.setDataSource(uri.getPath()); } else { remote = true; mp.setDataSource(url); } } mp.setLooping(looping); mp.setOnCompletionListener(this); mp.setOnErrorListener(this); mp.setOnInfoListener(this); mp.setOnBufferingUpdateListener(this); mp.prepare(); // Probably need to allow for Async setState(STATE_INITIALIZED); setVolume(volume); if (proxy.hasProperty(TiC.PROPERTY_TIME)) { setTime(TiConvert.toInt(proxy.getProperty(TiC.PROPERTY_TIME))); } } catch (Throwable t) { Log.w(LCAT, "Issue while initializing : ", t); release(); setState(STATE_STOPPED); } }
/** * Sets the data source as a content Uri. Call this method before the rest of the methods in this * class. This method may be time-consuming. * * @param context the Context to use when resolving the Uri * @param uri the Content URI of the data you want to play * @throws IllegalArgumentException if the Uri is invalid * @throws SecurityException if the Uri cannot be used due to lack of permission. */ public void setDataSource(Context context, Uri uri) throws IllegalArgumentException, SecurityException { if (uri == null) { throw new IllegalArgumentException(); } String scheme = uri.getScheme(); if (scheme == null || scheme.equals("file")) { setDataSource(uri.getPath()); return; } AssetFileDescriptor fd = null; try { ContentResolver resolver = context.getContentResolver(); try { fd = resolver.openAssetFileDescriptor(uri, "r"); } catch (FileNotFoundException e) { throw new IllegalArgumentException(); } if (fd == null) { throw new IllegalArgumentException(); } FileDescriptor descriptor = fd.getFileDescriptor(); if (!descriptor.valid()) { throw new IllegalArgumentException(); } // Note: using getDeclaredLength so that our behavior is the same // as previous versions when the content provider is returning // a full file. if (fd.getDeclaredLength() < 0) { setDataSource(descriptor); } else { setDataSource(descriptor, fd.getStartOffset(), fd.getDeclaredLength()); } return; } catch (SecurityException ex) { } finally { try { if (fd != null) { fd.close(); } } catch (IOException ioEx) { } } setDataSource(uri.toString()); }
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 void initBeepSound() { if (playBeep && mediaPlayer == null) { setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = 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 e) { mediaPlayer = null; } } }
private void a() { this.doCleanUp(); try { this.s = new MediaPlayer(); if (this.i) { this.s.setDataSource(this.c, Uri.parse(this.f)); } else if (this.k != 0L) { final FileInputStream fileInputStream = new FileInputStream(this.f); this.s.setDataSource(fileInputStream.getFD(), this.j, this.k); fileInputStream.close(); } else { final AssetManager assets = this.getResources().getAssets(); try { final AssetFileDescriptor openFd = assets.openFd(this.f); this.s.setDataSource( openFd.getFileDescriptor(), openFd.getStartOffset(), openFd.getLength()); openFd.close(); } catch (IOException ex2) { final FileInputStream fileInputStream2 = new FileInputStream(this.f); this.s.setDataSource(fileInputStream2.getFD()); fileInputStream2.close(); } } this.s.setDisplay(this.e); this.s.setOnBufferingUpdateListener((MediaPlayer.OnBufferingUpdateListener) this); this.s.setOnCompletionListener((MediaPlayer.OnCompletionListener) this); this.s.setOnPreparedListener((MediaPlayer.OnPreparedListener) this); this.s.setOnVideoSizeChangedListener((MediaPlayer.OnVideoSizeChangedListener) this); this.s.setAudioStreamType(3); this.s.prepare(); if (this.g == 0 || this.g == 1) { (this.t = new MediaController(this.c)) .setMediaPlayer((MediaController.MediaPlayerControl) this); this.t.setAnchorView((View) this.d); this.t.setEnabled(true); this.t.show(); } } catch (Exception ex) { if (com.unity3d.player.q.a) { a("error: " + ex.getMessage() + ex); } this.onDestroy(); } }
/** * Looks for the photo data item in entities. If found, a thumbnail will be stored. A larger photo * will also be stored if available. */ private void loadPhotoBinaryData(Contact contactData) { loadThumbnailBinaryData(contactData); // Try to load the large photo from a file using the photo URI. String photoUri = contactData.getPhotoUri(); if (photoUri != null) { try { final InputStream inputStream; final AssetFileDescriptor fd; final Uri uri = Uri.parse(photoUri); final String scheme = uri.getScheme(); if ("http".equals(scheme) || "https".equals(scheme)) { // Support HTTP urls that might come from extended directories inputStream = new URL(photoUri).openStream(); fd = null; } else { fd = getContext().getContentResolver().openAssetFileDescriptor(uri, "r"); inputStream = fd.createInputStream(); } byte[] buffer = new byte[16 * 1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { int size; while ((size = inputStream.read(buffer)) != -1) { baos.write(buffer, 0, size); } contactData.setPhotoBinaryData(baos.toByteArray()); } finally { inputStream.close(); if (fd != null) { fd.close(); } } return; } catch (IOException ioe) { // Just fall back to the case below. } } // If we couldn't load from a file, fall back to the data blob. contactData.setPhotoBinaryData(contactData.getThumbnailPhotoBinaryData()); }
public void playSound(Sound sound) { int resource = sound.getResourceId(); if (mPlayer != null) { if (mPlayer.isPlaying()) mPlayer.stop(); mPlayer.reset(); try { AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(resource); if (afd == null) return; mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mPlayer.prepare(); } catch (IOException | IllegalArgumentException | SecurityException e) { Log.e(TAG, e.getMessage()); } } else { mPlayer = MediaPlayer.create(mContext, resource); } mPlayer.start(); }
/** * Creates the beep MediaPlayer in advance so that the sound can be triggered with the least * latency possible. */ private void initBeepSound() { if (playBeep && mediaPlayer == null) { // The volume on STREAM_SYSTEM is not adjustable, and users found it too loud, // so we now play on the music stream. setVolumeControlStream(AudioManager.STREAM_MUSIC); mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setOnCompletionListener(beepListener); AssetFileDescriptor file = 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 e) { mediaPlayer = null; } } }
private void initBeepSound() { AssetFileDescriptor localAssetFileDescriptor; if ((this.playBeep) && (this.mediaPlayer == null)) { setVolumeControlStream(3); this.mediaPlayer = new MediaPlayer(); this.mediaPlayer.setAudioStreamType(3); this.mediaPlayer.setOnCompletionListener(this.beepListener); localAssetFileDescriptor = getResources().openRawResourceFd(2131099648); } try { this.mediaPlayer.setDataSource( localAssetFileDescriptor.getFileDescriptor(), localAssetFileDescriptor.getStartOffset(), localAssetFileDescriptor.getLength()); localAssetFileDescriptor.close(); this.mediaPlayer.setVolume(0.1F, 0.1F); this.mediaPlayer.prepare(); return; } catch (IOException localIOException) { while (true) this.mediaPlayer = null; } }
public static void playIntro(Context context) { try { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.stop(); mediaPlayer.release(); } mediaPlayer = new MediaPlayer(); AssetFileDescriptor descriptor = context.getAssets().openFd("intro.mp3"); mediaPlayer.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); mediaPlayer.setLooping(false); mediaPlayer.prepare(); mediaPlayer.start(); descriptor.close(); } catch (Exception e) { e.printStackTrace(); } }
/* * 后台播放背景音 */ private void playBackgroundMusic() { if (mplayer == null) { mplayer = new MediaPlayer(); try { AssetFileDescriptor afd = this.getAssets().openFd("angel.mp3"); // 获取音乐数据源 mplayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mplayer.setLooping(true); // 设为循环播放 } catch (IOException e) { e.printStackTrace(); } } try { if (mplayer.isPlaying()) { return; } mplayer.prepare(); mplayer.start(); } catch (Exception e) { e.printStackTrace(); } }
/* * アセットからデータを読み込む。 * @param context * @param filename * @return */ public static MediaPlayer loadAssetsSound(String filename) { if (LAppDefine.DEBUG_LOG) Log.d("", "Load sound : " + filename); final MediaPlayer player = new MediaPlayer(); try { final AssetFileDescriptor assetFileDescritorArticle = FileManager.openFd(filename); player.reset(); player.setDataSource( assetFileDescritorArticle.getFileDescriptor(), assetFileDescritorArticle.getStartOffset(), assetFileDescritorArticle.getLength()); player.setAudioStreamType(AudioManager.STREAM_MUSIC); assetFileDescritorArticle.close(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return player; }
@Override protected void onResume() { soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, SRC_QUALITY); soundPool.setOnLoadCompleteListener(this); aMgr = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); sid_background = soundPool.load(this, R.raw.crickets, PRIORITY); sid_chimp = soundPool.load(this, R.raw.chimp, PRIORITY); sid_rooster = soundPool.load(this, R.raw.rooster, PRIORITY); sid_roar = soundPool.load(this, R.raw.roar, PRIORITY); try { AssetFileDescriptor afd = this.getAssets().openFd("dogbark.mp3"); sid_bark = soundPool.load(afd.getFileDescriptor(), 0, afd.getLength(), PRIORITY); afd.close(); } catch (IOException e) { e.printStackTrace(); } // sid_bark = soundPool.load("/mnt/sdcard/dogbark.mp3", PRIORITY); super.onResume(); }
private boolean playFallbackRingtone() { if (mAudioManager.getStreamVolume(AudioAttributes.toLegacyStreamType(mAudioAttributes)) != 0) { int subId = RingtoneManager.getDefaultRingtoneSubIdByUri(mUri); if (subId != -1 && RingtoneManager.getActualRingtoneUriBySubId(mContext, subId) != null) { // Default ringtone, try fallback ringtone. try { AssetFileDescriptor afd = mContext.getResources().openRawResourceFd(com.android.internal.R.raw.fallbackring); if (afd != null) { mLocalPlayer = new MediaPlayer(); if (afd.getDeclaredLength() < 0) { mLocalPlayer.setDataSource(afd.getFileDescriptor()); } else { mLocalPlayer.setDataSource( afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength()); } mLocalPlayer.setAudioAttributes(mAudioAttributes); mLocalPlayer.prepare(); mLocalPlayer.start(); afd.close(); return true; } else { Log.e(TAG, "Could not load fallback ringtone"); } } catch (IOException ioe) { destroyLocalPlayer(); Log.e(TAG, "Failed to open fallback ringtone"); } catch (NotFoundException nfe) { Log.e(TAG, "Fallback ringtone does not exist"); } } else { Log.w(TAG, "not playing fallback for " + mUri); } } return false; }
public void doMusic() { AssetFileDescriptor descriptor = null; try { descriptor = getAssets().openFd("intro.MP3"); } catch (Exception e) { e.printStackTrace(); } try { MP.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); } catch (Exception e) { e.printStackTrace(); } try { descriptor.close(); } catch (Exception e) { e.printStackTrace(); } try { MP.prepare(); } catch (Exception e) { e.printStackTrace(); } if (MP != null) { MP.setVolume(0f, 0f); MP.setLooping(true); MP.start(); } descriptor = null; try { descriptor = getAssets().openFd("up.MP3"); } catch (Exception e) { e.printStackTrace(); } try { MP_UP.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); } catch (Exception e) { e.printStackTrace(); } try { descriptor.close(); } catch (Exception e) { e.printStackTrace(); } try { MP_UP.prepare(); } catch (Exception e) { e.printStackTrace(); } if (MP_UP != null) MP_UP.setVolume(1f, 1f); descriptor = null; try { descriptor = getAssets().openFd("pong.MP3"); } catch (Exception e) { e.printStackTrace(); } try { MP_PONG.setDataSource( descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); } catch (Exception e) { e.printStackTrace(); } try { descriptor.close(); } catch (Exception e) { e.printStackTrace(); } try { MP_PONG.prepare(); } catch (Exception e) { e.printStackTrace(); } if (MP_PONG != null) MP_PONG.setVolume(1f, 1f); }
@Override protected Integer doInBackground(Void... params) { byte[] buffer = new byte[4096]; int bytesRead; AssetFileDescriptor fdout = null; InputStream is = null; OutputStream os = null; try { // Delete the current picture ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); ops.add( ContentProviderOperation.newUpdate( Data.CONTENT_URI .buildUpon() .appendQueryParameter(RawContacts.ACCOUNT_NAME, account) .appendQueryParameter(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE) .build()) .withSelection(GroupMembership.RAW_CONTACT_ID + " = " + pickedRawContact, null) .withValue(Photo.PHOTO, null) .build()); try { getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); } catch (RemoteException e1) { } catch (OperationApplicationException e1) { } // Store the image using android API as to update its database is = new FileInputStream(cropTemp); Uri rawContactPhotoUri = Uri.withAppendedPath( ContentUris.withAppendedId(RawContacts.CONTENT_URI, pickedRawContact), RawContacts.DisplayPhoto.CONTENT_DIRECTORY); fdout = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "w"); os = fdout.createOutputStream(); bytesRead = is.read(buffer); while (bytesRead >= 0) { os.write(buffer, 0, bytesRead); bytesRead = is.read(buffer); if (isCancelled()) return RESULT_CANCELLED; } os.close(); fdout.close(); is.close(); // Wait until its file ID is available int fileId = -1; Uri contactsUri = ContactsContract.Data.CONTENT_URI .buildUpon() .appendQueryParameter(RawContacts.ACCOUNT_NAME, account) .appendQueryParameter(RawContacts.ACCOUNT_TYPE, ACCOUNT_TYPE) .build(); int retryTime = 0; for (; retryTime < WAIT_TIME_DB; retryTime += WAIT_TIME_INT) { Cursor cursor = getContentResolver() .query( contactsUri, new String[] {Photo.PHOTO_FILE_ID, GroupMembership.RAW_CONTACT_ID}, GroupMembership.RAW_CONTACT_ID + " = ?", new String[] {pickedRawContact + ""}, null); try { if (cursor.moveToFirst()) { int colIndex = cursor.getColumnIndex(Photo.PHOTO_FILE_ID); if (!cursor.isNull(colIndex)) { fileId = cursor.getInt(colIndex); break; } } } finally { cursor.close(); } if (isCancelled()) return RESULT_CANCELLED; } if (fileId < 0) { Log.e(TAG, "File ID didn't show up in db after saving"); return RESULT_IO_ERROR; } // Wait until the actual file is available boolean fileAvailable = false; for (; retryTime < WAIT_TIME_DB; retryTime += WAIT_TIME_INT) { try { fdout = getContentResolver().openAssetFileDescriptor(rawContactPhotoUri, "r"); is = fdout.createInputStream(); is.close(); fdout.close(); fileAvailable = true; break; } catch (FileNotFoundException e) { } finally { try { is.close(); } catch (IOException e) { } try { fdout.close(); } catch (IOException e) { } } if (isCancelled()) return RESULT_CANCELLED; } if (!fileAvailable) return RESULT_IO_ERROR; // Atomically replace the image file if (!rootReplaceImage(cropTemp.getAbsolutePath(), fileId)) return RESULT_NO_ROOT; return RESULT_SUCCESS; } catch (InterruptedException e) { return RESULT_IO_ERROR; } catch (IOException e) { e.printStackTrace(); return RESULT_IO_ERROR; } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (os != null) os.close(); } catch (IOException e) { } try { if (fdout != null) fdout.close(); } catch (IOException e) { } } }
/** * This is a private method which is used by this class to attach a file to the media player. It * is called by either playAudio or playIntervalOfAudio (if its a new audio file or the media * player is null). * * <p>Preconditions: the mediaplayer is null. IF both cueTo and endAt are 0 then it will play the * entire audio * * @param urlstring The file name either on the sdcard, on the web, or in the assets folder. * @param cueTo The position in milliseconds to play from. * @param endAt The position in milliseconds to end playback. If then the audio will play * completely. */ @JavascriptInterface protected void setAudioFile(final String urlstring, final int cueTo, final int endAt) { this.mMediaPlayer = new MediaPlayer(); try { if (urlstring.contains("android_asset")) { String tempurlstring = urlstring.replace("file:///android_asset/", ""); this.mAudioPlaybackFileUrl = tempurlstring; AssetFileDescriptor afd = this.mContext.getAssets().openFd(this.mAudioPlaybackFileUrl); this.mMediaPlayer.setDataSource( afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } else if (urlstring.contains("sdcard")) { this.mAudioPlaybackFileUrl = urlstring; this.mMediaPlayer.setDataSource(this.mAudioPlaybackFileUrl); } else { if (this.D) Log.d(this.TAG, "This is what the audiofile looked like:" + urlstring); String tempurlstring = urlstring.replaceFirst("/", this.mAssetsPrefix); this.mAudioPlaybackFileUrl = tempurlstring; if (this.D) Log.d(this.TAG, "This is what the audiofile looks like:" + this.mAudioPlaybackFileUrl); AssetFileDescriptor afd = this.mContext.getAssets().openFd(this.mAudioPlaybackFileUrl); this.mMediaPlayer.setDataSource( afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } this.mMediaPlayer.setOnPreparedListener( new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { if (JavaScriptInterface.this.D) Log.d(JavaScriptInterface.this.TAG, "Starting to play the audio."); if (cueTo == 0 && endAt == 0) { JavaScriptInterface.this.mMediaPlayer.start(); } else { JavaScriptInterface.this.playIntervalOfAudio( JavaScriptInterface.this.mAudioPlaybackFileUrl, cueTo, endAt); } } }); this.mMediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (JavaScriptInterface.this.D) Log.d( JavaScriptInterface.this.TAG, "Audio playback is complete, releasing the audio."); JavaScriptInterface.this.mMediaPlayer.release(); JavaScriptInterface.this.mMediaPlayer = null; // getUIParent().loadUrlToWebView(); LoadUrlToWebView v = new LoadUrlToWebView(); v.setMessage( "javascript:OPrime.hub.publish('playbackCompleted','" + JavaScriptInterface.this.mAudioPlaybackFileUrl + "');"); v.execute(); } }); this.mMediaPlayer.prepareAsync(); } catch (IllegalArgumentException e) { Log.e(this.TAG, "There was a problem with the sound " + e.getMessage()); e.printStackTrace(); } catch (IllegalStateException e) { Log.e(this.TAG, "There was a problem with the sound, starting anyway" + e.getMessage()); this.mMediaPlayer.start(); // TODO check why this is still here. } catch (IOException e) { Log.e(this.TAG, "There was a problem with the sound " + e.getMessage()); e.printStackTrace(); } catch (Exception e) { Log.e(this.TAG, "There was a problem with the sound " + e.getMessage()); e.printStackTrace(); } }