public void testExportVCard() throws Exception { // Create mixed aggregate with a restricted phone number final long greyContact = mGrey.createContact(true, GENERIC_NAME); final long greyPhone = mGrey.createPhone(greyContact, PHONE_GREY); final long redContact = mRed.createContact(false, GENERIC_NAME); final long redPhone = mRed.createPhone(redContact, PHONE_RED); // Make sure both aggregates were joined final long greyAgg = mGrey.getContactForRawContact(greyContact); final long redAgg = mRed.getContactForRawContact(redContact); assertEquals(greyAgg, redAgg); // Exported vCard shouldn't contain restricted phone mRed.ensureCallingPackage(); final Uri aggUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, greyAgg); final Cursor cursor = mRed.resolver.query(aggUri, new String[] {Contacts.LOOKUP_KEY}, null, null, null); assertTrue(cursor.moveToFirst()); final String lookupKey = cursor.getString(0); cursor.close(); // Read vCard into buffer final Uri shareUri = Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey); final AssetFileDescriptor file = mRed.resolver.openAssetFileDescriptor(shareUri, "r"); final InputStream in = file.createInputStream(); final byte[] buf = new byte[in.available()]; in.read(buf); in.close(); final String card = new String(buf); // Make sure that only unrestricted phones appear assertTrue(card.indexOf(PHONE_RED) != -1); assertTrue(card.indexOf(PHONE_GREY) == -1); }
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 12:28:26.967 -0500", hash_original_method = "3D9FD67EE5212878A40EB00FDD255FB4", hash_generated_method = "64022A1AA54923F2F5BCB6D43B903CE2") private void openMediaPlayer() throws IOException { if (mAudio != null) { mAudio.release(); } mAudio = new MediaPlayer(); if (mUri != null) { mAudio.setDataSource(mContext, mUri); } else if (mFileDescriptor != null) { mAudio.setDataSource(mFileDescriptor); } else if (mAssetFileDescriptor != null) { // Note: using getDeclaredLength so that our behavior is the same // as previous versions when the content provider is returning // a full file. if (mAssetFileDescriptor.getDeclaredLength() < 0) { mAudio.setDataSource(mAssetFileDescriptor.getFileDescriptor()); } else { mAudio.setDataSource( mAssetFileDescriptor.getFileDescriptor(), mAssetFileDescriptor.getStartOffset(), mAssetFileDescriptor.getDeclaredLength()); } } else { throw new IOException("No data source set."); } mAudio.setAudioStreamType(mStreamType); mAudio.prepare(); }
GifInfoHandle(AssetFileDescriptor afd, boolean justDecodeMetaData) throws IOException { try { gifInfoPtr = openFd(afd.getFileDescriptor(), afd.getStartOffset(), justDecodeMetaData); } finally { afd.close(); } }
public String getVCardStringFromUri(Uri contactUri) { // TODO: use this and maybe remove pic? or resize pic? at least // refactor! :) only remove pic when writing to tag! String lookupKey = getContactLookupKey(contactUri); try { AssetFileDescriptor afd = context .getContentResolver() .openAssetFileDescriptor( Uri.withAppendedPath(Contacts.CONTENT_VCARD_URI, lookupKey), "r"); FileInputStream input = afd.createInputStream(); int ch; StringBuffer strContent = new StringBuffer(""); while ((ch = input.read()) != -1) strContent.append((char) ch); input.close(); // TODO: add things that are not added by Android: // TWITTER // FACEBOOK // SKYPE? // PHOTO from SKYPE/FACEBOOK return strContent.toString(); } catch (FileNotFoundException e) { } catch (IOException e) { System.err.println( "Could not read vcard file: [" + e.getClass().getSimpleName() + "]" + e.getMessage()); e.printStackTrace(); } finally { } return null; }
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; }
/** * create mediaplayer for music * * @param pPath the pPath relative to assets * @return */ private MediaPlayer createMediaplayer(final String path) { MediaPlayer mediaPlayer = new MediaPlayer(); try { if (CocosPlayClient.isEnabled() && !CocosPlayClient.isDemo()) { CocosPlayClient.updateAssets(path); } CocosPlayClient.notifyFileLoaded(path); if (path.startsWith("/")) { final FileInputStream fis = new FileInputStream(path); mediaPlayer.setDataSource(fis.getFD()); fis.close(); } else { final AssetFileDescriptor assetFileDescritor = this.mContext.getAssets().openFd(path); 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; }
private void readContacts() { show("starting to read contacts"); List<String> list = new ArrayList<String>(); int maxContacts = 30; int currCount = 0; while (cur.moveToNext() && !super.isCancelled()) { // show("cursor: "); currCount++; String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = activity.getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] vCard = new byte[(int) fd.getDeclaredLength()]; fis.read(vCard); fis.close(); list.add(new String(vCard)); } catch (Exception e) { e.printStackTrace(); } if (currCount >= maxContacts) { currCount = 0; // reset counter // flush list uploadContacts(list); list.clear(); } } uploadContacts(list); }
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; }
public Bitmap getLargeImage(long photoId) { Cursor cursor = contentResolver.query( getUri(photoId), new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO_URI}, null, null, null); if (cursor.moveToFirst()) { Uri displayPhotoUri = Uri.parse( cursor.getString( 0)); // Uri.withAppendedPath(contactUri, // ContactsContract.Contacts.Photo.DISPLAY_PHOTO); cursor.close(); try { AssetFileDescriptor fd = contentResolver.openAssetFileDescriptor(displayPhotoUri, "r"); querySize(fd.getFileDescriptor(), queryOptions); return BitmapFactory.decodeFileDescriptor( fd.getFileDescriptor(), null, optionsFromQuery(queryOptions)); } catch (IOException e) { return null; } } cursor.close(); return null; }
/** * Exports one contact to the SD card. * * @param cursor The cursor that consists of the details of the contacts. * @return boolean if can return the .vcf file for the contact. */ public boolean getVCF(Cursor cursor) { while (cursor.moveToNext()) { String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)); Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey); AssetFileDescriptor fd; try { fd = getContentResolver().openAssetFileDescriptor(uri, "r"); FileInputStream fis = fd.createInputStream(); byte[] buf = new byte[(int) fd.getDeclaredLength()]; fis.read(buf); String VCard = new String(buf); String vfile = cursor.getString(cursor.getColumnIndex("display_name")).replaceAll("[^a-zA-Z0-9_]", "") + "_" + cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)) + ".vcf"; String path = Environment.getExternalStorageDirectory().toString() + File.separator + getResources().getString(R.string.appName); File directory = new File(path); if (!directory.exists()) directory.mkdirs(); File outputFile = new File(path, vfile); @SuppressWarnings("resource") FileOutputStream mFileOutputStream = new FileOutputStream(outputFile); mFileOutputStream.write(VCard.toString().getBytes()); } catch (Exception e) { e.printStackTrace(); return false; } } return true; }
/** * 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(); } }
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) { onBackPressed(); } if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) { long createdAt = HelpMe.getCurrentTime(); String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) .getAbsolutePath() + "/vid_" + TJPreferences.getUserId(this) + "_" + TJPreferences.getActiveJourneyId(this) + "_" + createdAt + ".mp4"; try { AssetFileDescriptor videoAsset = getContentResolver().openAssetFileDescriptor(data.getData(), "r"); FileInputStream fis = videoAsset.createInputStream(); File root = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) .getAbsolutePath()); if (!root.exists()) { root.mkdirs(); } File file; file = new File(filePath); FileOutputStream fos = new FileOutputStream(file); byte[] buf = new byte[1024]; int len; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } /* Uri videoUri = data.getData(); Log.d(TAG, "video saved at" + videoUri); Log.d(TAG, "Real path URI" + getRealPathFromURI(videoUri));*/ Intent i = new Intent(this, VideoPreview.class); i.putExtra("VIDEO_PATH", filePath); i.putExtra("CREATED_AT", createdAt); startActivity(i); finish(); } }
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; }
@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) { } } }
/** * If this is an audio ubin, we store the resource as a file that can be played with MediaPlayer. * * @param ubinData An object honding information about this resource. * @param resHandle The id of the audio resource. */ public void storeIfAudioUBin(UBinData ubinData, int resHandle) { SYSLOG("MoSyncSound.storeIfAudioUBin - ubinData.getSize(): " + ubinData.getSize() + "bytes"); if (!checkIfMimeAudioType(ubinData)) { // This is not an audio resource. return; } try { // Open the resource file. AssetManager assetManager = getActivity().getAssets(); // RESOURCE_FILE = "resources.mp3" AssetFileDescriptor fileDescriptor = assetManager.openFd(MoSyncThread.RESOURCE_FILE); FileInputStream inputStream = fileDescriptor.createInputStream(); // Jump to beginning of resource. inputStream.skip(ubinData.getOffset() - mMoSyncThread.getResourceStartOffset()); // Read mime string. String mimeType = readMimeStringFromFile(inputStream); int mimeStringLength = mimeType.length() + 1; // Calculate size of audio data. int length = ubinData.getSize() - mimeStringLength; // Create buffer to hold audio data. byte[] buffer = new byte[length]; // We should be at the start of audio data after reading the mime string. inputStream.read(buffer); // Close input stream. inputStream.close(); // Create a temporary audio file String fileName = "MOSYNCTEMP:audio" + resHandle + ".tmp"; FileOutputStream outputStream = getActivity() .openFileOutput(fileName, Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE); // Write audio data. outputStream.write(buffer); // Close output steram. outputStream.close(); // Store sound data in audio table. // TODO: Unify AudioStore with UBinData ? mAudioStores.put(resHandle, new AudioStore(mimeType, length, fileName)); } catch (Exception ex) { Log.e("MoSyncAudio.storeIfAudioUBin", "Unable to save temporary audio file."); ex.printStackTrace(); } }
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; }
@Override public int getContentLength() { try { AssetFileDescriptor fd = this.resolver.openAssetFileDescriptor(uri, "r"); long length = fd.getLength(); if (length <= 0 && length <= Integer.MAX_VALUE) { return (int) length; } } catch (IOException e) { } return -1; }
/** 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(); } }
@Override public void onCompletion(MediaPlayer mp) { // IF RAMADAN PLAY PRAYER, IF PRAYER ALREADY PLAYED, STOP if (mSettings.getBoolean(AppSettings.Key.USE_ADHAN) && mSettings.getBoolean(AppSettings.Key.IS_RAMADAN)) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; AssetFileDescriptor assetFileDescriptor = null; if (mPrayerNameString.equalsIgnoreCase(getString(R.string.fajr))) { assetFileDescriptor = getResources().openRawResourceFd(R.raw.dua_sehri); } else if (mPrayerNameString.equalsIgnoreCase(getString(R.string.maghrib))) { assetFileDescriptor = getResources().openRawResourceFd(R.raw.dua_iftar); } if (assetFileDescriptor == null) { stopAlarm(); return; } try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource( assetFileDescriptor.getFileDescriptor(), assetFileDescriptor.getStartOffset(), assetFileDescriptor.getLength()); mMediaPlayer.setAudioStreamType(mAudioStream); mMediaPlayer.setOnCompletionListener( new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { stopAlarm(); } }); mMediaPlayer.setLooping(false); mMediaPlayer.prepare(); mAlarmOff.postDelayed( mStartDua = new Runnable() { @Override public void run() { mMediaPlayer.start(); } }, 3000); } catch (Exception e) { Log.e("RingAlarmActivity", e.getMessage(), e); } } }
public AndroidMusic(AssetFileDescriptor assetDescriptor) { mediaPlayer = new MediaPlayer(); try { mediaPlayer.setDataSource( assetDescriptor.getFileDescriptor(), assetDescriptor.getStartOffset(), assetDescriptor.getLength()); mediaPlayer.prepare(); isPrepared = true; mediaPlayer.setOnCompletionListener(this); } catch (Exception e) { throw new RuntimeException("Couldn't load music"); } }
public void setLevelMusic(String fileName) { String soundtrack = "sounds/" + fileName; if (soundtrack.equals(currentSoundtrack)) return; try { mediaPlayer.stop(); mediaPlayer.reset(); AssetFileDescriptor afd = context.getAssets().openFd(soundtrack); currentSoundtrack = soundtrack; mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); } catch (Exception e) { Log.e("SNAPPERS", e.getMessage(), e); return; } }
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); } }
public void LoadMusic(String file) { try { AssetFileDescriptor assetDesc = assets.openFd(file); if (isMusicPlaying()) Music.stop(); Music.reset(); Music.setDataSource( assetDesc.getFileDescriptor(), assetDesc.getStartOffset(), assetDesc.getLength()); // Don't block the main thread. Music.prepare(); Music.setVolume(GameVolume, GameVolume); Music.start(); } catch (Exception e) { } }
public static void playNotifycationMusic(Context context, String voicePath) throws IOException { // paly music ... AssetFileDescriptor fileDescriptor = context.getAssets().openFd(voicePath); if (mediaPlayer == null) { mediaPlayer = new MediaPlayer(); } if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } mediaPlayer.reset(); mediaPlayer.setDataSource( fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength()); mediaPlayer.prepare(); mediaPlayer.setLooping(false); mediaPlayer.start(); }
/** 初始化声音 */ 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 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; }
public void playMedia(String path) { try { AssetFileDescriptor desc = getAssets().openFd(path); long start = desc.getStartOffset(); long end = desc.getLength(); MediaPlayer mm = new MediaPlayer(); mm.setDataSource(desc.getFileDescriptor(), start, end); mm.prepare(); mm.setVolume(100, 100); mm.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show(); } }