List of usage examples for android.content.res AssetFileDescriptor getFileDescriptor
public FileDescriptor getFileDescriptor()
From source file:com.xlythe.engine.theme.Theme.java
public static Typeface getFont(Context context, String name) { String key = getKey(context) + "_" + name; if (TYPEFACE_MAP.containsKey(key)) { return TYPEFACE_MAP.get(key); }/*from ww w. jav a2s . co m*/ String[] extensions = { ".ttf", ".otf" }; for (String s : extensions) { try { // Use cursor loader to grab font String url = getPackageName() + ".FileProvider/" + name + s; Uri uri = Uri.parse("content://" + url); ContentResolver cr = context.getContentResolver(); AssetFileDescriptor a = cr.openAssetFileDescriptor(uri, null); FileInputStream in = new FileInputStream(a.getFileDescriptor()); in.skip(a.getStartOffset()); File file = new File(context.getCacheDir(), name + s); file.createNewFile(); FileOutputStream fOutput = new FileOutputStream(file); byte[] dataBuffer = new byte[1024]; int readLength = 0; while ((readLength = in.read(dataBuffer)) != -1) { fOutput.write(dataBuffer, 0, readLength); } in.close(); fOutput.close(); // Try/catch for broken fonts Typeface t = Typeface.createFromFile(file); TYPEFACE_MAP.put(key, t); return TYPEFACE_MAP.get(key); } catch (Exception e) { // Do nothing here } } TYPEFACE_MAP.put(key, null); return TYPEFACE_MAP.get(key); }
From source file:Main.java
public static Bitmap decodeSampledBitmapFromFile(Resources res, ContentResolver contentResolver, File file, float reqWidthInDip, float reqHeightInDip) throws IOException { Bitmap bitmap;/*from w ww .j ava2 s . com*/ AssetFileDescriptor fileDescriptor; int reqWidthInPixel = (int) dipToPixels(res, reqWidthInDip); int reqHeightInPixel = (int) dipToPixels(res, reqHeightInDip); fileDescriptor = contentResolver.openAssetFileDescriptor(Uri.fromFile(file), "r"); // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidthInPixel, reqHeightInPixel); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options); fileDescriptor.close(); return bitmap; }
From source file:com.xlythe.engine.theme.Theme.java
public static long getDurationOfSound(Context context, Theme.Res res) { int millis = 0; MediaPlayer mp = new MediaPlayer(); try {/* w ww. j ava2 s. com*/ AssetFileDescriptor afd; int id = getId(context, res.getType(), res.getName()); if (id == 0) { id = context.getResources().getIdentifier(res.getName(), res.getType(), context.getPackageName()); afd = context.getResources().openRawResourceFd(id); } afd = getThemeContext(context).getResources().openRawResourceFd(id); mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mp.prepare(); millis = mp.getDuration(); } catch (Exception e) { e.printStackTrace(); } finally { mp.release(); mp = null; } return millis; }
From source file:com.adkdevelopment.simpleflashlightadfree.ui.EmergencyFragment.java
/** * Starts emergency sound from assets/* w w w . ja v a2s . c o m*/ */ public void emergencySignal() { try { if (mMediaPlayer != null && mMediaPlayer.isPlaying() && status == FlashlightService.STATUS_OFF) { mMediaPlayer.stop(); mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; mLinearLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.colorBackground)); } else if (status == FlashlightService.STATUS_BLINK) { final AnimationDrawable drawable = new AnimationDrawable(); final Handler handler = new Handler(); drawable.addFrame(new ColorDrawable(Color.RED), 400); drawable.addFrame(new ColorDrawable(Color.BLUE), 400); drawable.setOneShot(false); mLinearLayout.setBackground(drawable); handler.postDelayed(new Runnable() { @Override public void run() { drawable.start(); } }, 100); mMediaPlayer = new MediaPlayer(); AssetFileDescriptor descriptor = getActivity().getAssets().openFd("sews.mp3"); mMediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength()); descriptor.close(); mMediaPlayer.prepare(); mMediaPlayer.setVolume(1f, 1f); mMediaPlayer.setLooping(true); mMediaPlayer.start(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:it.interfree.leonardoce.bootreceiver.AlarmKlaxon.java
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();/* w w w. j a v a 2 s . c om*/ } }
From source file:com.wsi.audiodemo.ScrollingActivity.java
private void playSound2(String assetName) { try {/*from ww w .ja v a2s. c om*/ // Syntax : android.resource://[package]/[res type]/[res name] // Example : Uri.parse("android.resource://com.my.package/raw/sound1"); // // Syntax : android.resource://[package]/[resource_id] // Example : Uri.parse("android.resource://com.my.package/" + R.raw.sound1); String RESOURCE_PATH = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"; String path; if (false) { path = RESOURCE_PATH + getPackageName() + "/raw/" + assetName; } else { int resID = getResources().getIdentifier(assetName, "raw", getPackageName()); path = RESOURCE_PATH + getPackageName() + File.separator + resID; } Uri soundUri = Uri.parse(path); mSoundName.setText(path); mMediaPlayer = new MediaPlayer(); if (true) { mMediaPlayer.setDataSource(getApplicationContext(), soundUri); mMediaPlayer.prepare(); } else if (false) { // How to load external audio files. // "/sdcard/sample.mp3"; // "http://www.bogotobogo.com/Audio/sample.mp3"; mMediaPlayer.setDataSource(path); mMediaPlayer.prepare(); } else { ContentResolver resolver = getContentResolver(); AssetFileDescriptor afd = resolver.openAssetFileDescriptor(soundUri, "r"); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); } mMediaPlayer.start(); } catch (Exception ex) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }
From source file:org.cocos2dx.lib.Cocos2dxMusic.java
/** * create mediaplayer for music/*from w ww . j a v a 2 s . c o m*/ * @param path the path relative to assets * @return */ private MediaPlayer createMediaplayerFromAssets(String path) { MediaPlayer mediaPlayer = new MediaPlayer(); try { if (path.startsWith("/")) { mediaPlayer.setDataSource(path); } else { AssetFileDescriptor assetFileDescritor = mContext.getAssets().openFd(path); mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength()); } mediaPlayer.prepare(); mediaPlayer.setVolume(mLeftVolume, mRightVolume); } catch (Exception e) { mediaPlayer = null; Log.e(TAG, "error: " + e.getMessage(), e); } return mediaPlayer; }
From source file:com.wsi.audiodemo.ScrollingActivity.java
private void playSound3(String assetName) { try {/* w w w . ja v a 2 s .c o m*/ AssetFileDescriptor afd = getAssets().openFd("sounds/" + assetName + ".mp3"); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close(); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (Exception ex) { Toast.makeText(this, ex.getMessage(), Toast.LENGTH_LONG).show(); } }
From source file:com.wifi.brainbreaker.mydemo.http.ModAssetServer.java
public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;//from w ww. j a va2s . c o m final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }
From source file:net.facework.core.http.ModAssetServer.java
@Override public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { AbstractHttpEntity body = null;// w w w. j ava2 s .com final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } final String url = URLDecoder.decode(request.getRequestLine().getUri()); if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] entityContent = EntityUtils.toByteArray(entity); Log.d(TAG, "Incoming entity content (bytes): " + entityContent.length); } final String location = "www" + (url.equals("/") ? "/index.htm" : url); response.setStatusCode(HttpStatus.SC_OK); try { Log.i(TAG, "Requested: \"" + url + "\""); // Compares the Last-Modified date header (if present) with the If-Modified-Since date if (request.containsHeader("If-Modified-Since")) { try { Date date = DateUtils.parseDate(request.getHeaders("If-Modified-Since")[0].getValue()); if (date.compareTo(mServer.mLastModified) <= 0) { // The file has not been modified response.setStatusCode(HttpStatus.SC_NOT_MODIFIED); return; } } catch (DateParseException e) { e.printStackTrace(); } } // We determine if the asset is compressed try { AssetFileDescriptor afd = mAssetManager.openFd(location); // The asset is not compressed FileInputStream fis = new FileInputStream(afd.getFileDescriptor()); fis.skip(afd.getStartOffset()); body = new InputStreamEntity(fis, afd.getDeclaredLength()); Log.d(TAG, "Serving uncompressed file " + "www" + url); } catch (FileNotFoundException e) { // The asset may be compressed // AAPT compresses assets so first we need to uncompress them to determine their length InputStream stream = mAssetManager.open(location, AssetManager.ACCESS_STREAMING); ByteArrayOutputStream buffer = new ByteArrayOutputStream(64000); byte[] tmp = new byte[4096]; int length = 0; while ((length = stream.read(tmp)) != -1) buffer.write(tmp, 0, length); body = new InputStreamEntity(new ByteArrayInputStream(buffer.toByteArray()), buffer.size()); stream.close(); Log.d(TAG, "Serving compressed file " + "www" + url); } body.setContentType(getMimeMediaType(url) + "; charset=UTF-8"); response.addHeader("Last-Modified", DateUtils.formatDate(mServer.mLastModified)); } catch (IOException e) { // File does not exist response.setStatusCode(HttpStatus.SC_NOT_FOUND); body = new EntityTemplate(new ContentProducer() { @Override public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write("<html><body><h1>"); writer.write("File "); writer.write("www" + url); writer.write(" not found"); writer.write("</h1></body></html>"); writer.flush(); } }); Log.d(TAG, "File " + "www" + url + " not found"); body.setContentType("text/html; charset=UTF-8"); } response.setEntity(body); }