Example usage for android.content.res AssetFileDescriptor getLength

List of usage examples for android.content.res AssetFileDescriptor getLength

Introduction

In this page you can find the example usage for android.content.res AssetFileDescriptor getLength.

Prototype

public long getLength() 

Source Link

Document

Returns the total number of bytes of this asset entry's data.

Usage

From source file:com.wsi.audiodemo.ScrollingActivity.java

private void playSound3(String assetName) {
    try {/*from   w w  w  .j  a va 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:org.cocos2dx.lib.Cocos2dxMusic.java

/**
 * create mediaplayer for music/*  w ww.  ja v a  2 s  .  c om*/
 * @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.zetterstrom.android.soundboarder.MainActivity.java

public void playSound(AssetFileDescriptor afd) {
    if (mMediaPlayer != null) {
        try {/*w w  w.j  a  v a 2  s .  c  o  m*/
            if (mMediaPlayer.isPlaying())
                mMediaPlayer.stop();
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IllegalArgumentException e) {
            Toast.makeText(this, "Error Playing Sound Byte", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Toast.makeText(this, "Error Playing Sound Byte", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(this, "Error Playing Sound Byte", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    } else {
        Toast.makeText(this, "Error Playing Sound Byte", Toast.LENGTH_SHORT).show();
    }
}

From source file:org.cyanogenmod.theme.chooser.AudiblePreviewFragment.java

private MediaPlayer initAudibleMediaPlayer(AssetFileDescriptor afd, int type) throws IOException {
    MediaPlayer mp = mMediaPlayers.get(type);
    if (mp == null) {
        mp = new MediaPlayer();
        mMediaPlayers.put(type, mp);/*from   w ww  .ja v  a 2s .co m*/
    } else {
        mp.reset();
    }
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mp.prepare();
    mp.setOnCompletionListener(mPlayCompletionListener);
    return mp;
}

From source file:edu.stanford.junction.sample.partyware.ImgurUploadService.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * //ww w  .  j  a va2  s  .  c  o  m
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.imgur_upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();

        Random rng = new Random();
        String key = API_KEYS[rng.nextInt(API_KEYS.length)];
        hout.println(key);

        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
            mNotificationManager.cancelAll();
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:com.Anderson.example.games.tanc.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);//from  w w  w.  j  ava  2  s  . co  m
    // Create the Google API Client with access to Games
    mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(Games.API).addScope(Games.SCOPE_GAMES).build();

    mGoogleApiClient.connect();
    mMainMenuFragment = new MainMenuFragment();
    mGameplayFragment = new GameplayFragment();
    mWinFragment = new WinFragment();
    mListFragment = new com.Anderson.example.games.tanc.ListFragment();
    // listen to fragment events
    mListFragment.setListener(this);
    mMainMenuFragment.setListener(this);
    mGameplayFragment.setListener(this);
    mWinFragment.setListener(this);
    // add initial fragment (welcome fragment)
    getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, mMainMenuFragment).commit();
    try {
        AssetFileDescriptor afd = getAssets().openFd("sounds/backgroundSound.mp3");
        bg.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        bg.prepare();
        bg.setLooping(true);
        bg.setVolume(20, 20);
        bg.start();
        afd = getAssets().openFd("sounds/buttonSound.wav");
        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // IMPORTANT: if this Activity supported rotation, we'd have to be
    // more careful about adding the fragment, since the fragment would
    // already be there after rotation and trying to add it again would
    // result in overlapping fragments. But since we don't support rotation,
    // we don't deal with that for code simplicity.
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * This method uploads an image from the given uri. It does the uploading in
 * small chunks to make sure it doesn't over run the memory.
 * /*from w w  w.j a va2 s  .  c o  m*/
 * @param uri
 *            image location
 * @return map containing data from interaction
 */
private String readPictureDataAndUpload(final Uri uri) {
    Log.i(this.getClass().getName(), "in readPictureDataAndUpload(Uri)");
    try {
        final AssetFileDescriptor assetFileDescriptor = getContentResolver().openAssetFileDescriptor(uri, "r");
        final int totalFileLength = (int) assetFileDescriptor.getLength();
        assetFileDescriptor.close();

        // Create custom progress notification
        mProgressNotification = new Notification(R.drawable.icon, getString(R.string.upload_in_progress),
                System.currentTimeMillis());
        // set as ongoing
        mProgressNotification.flags |= Notification.FLAG_ONGOING_EVENT;
        // set custom view to notification
        mProgressNotification.contentView = generateProgressNotificationView(0, totalFileLength);
        //empty intent for the notification
        final Intent progressIntent = new Intent();
        final PendingIntent contentIntent = PendingIntent.getActivity(this, 0, progressIntent, 0);
        mProgressNotification.contentIntent = contentIntent;
        // add notification to manager
        mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);

        final InputStream inputStream = getContentResolver().openInputStream(uri);

        final String boundaryString = "Z." + Long.toHexString(System.currentTimeMillis())
                + Long.toHexString((new Random()).nextLong());
        final String boundary = "--" + boundaryString;
        final HttpURLConnection conn = (HttpURLConnection) (new URL("http://imgur.com/api/upload.json"))
                .openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-type", "multipart/form-data; boundary=\"" + boundaryString + "\"");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setChunkedStreamingMode(CHUNK_SIZE);
        final OutputStream hrout = conn.getOutputStream();
        final PrintStream hout = new PrintStream(hrout);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"key\"");
        hout.println("Content-Type: text/plain");
        hout.println();
        hout.println(API_KEY);
        hout.println(boundary);
        hout.println("Content-Disposition: form-data; name=\"image\"");
        hout.println("Content-Transfer-Encoding: base64");
        hout.println();
        hout.flush();
        {
            final Base64OutputStream bhout = new Base64OutputStream(hrout);
            final byte[] pictureData = new byte[READ_BUFFER_SIZE_BYTES];
            int read = 0;
            int totalRead = 0;
            long lastLogTime = 0;
            while (read >= 0) {
                read = inputStream.read(pictureData);
                if (read > 0) {
                    bhout.write(pictureData, 0, read);
                    totalRead += read;
                    if (lastLogTime < (System.currentTimeMillis() - PROGRESS_UPDATE_INTERVAL_MS)) {
                        lastLogTime = System.currentTimeMillis();
                        Log.d(this.getClass().getName(), "Uploaded " + totalRead + " of " + totalFileLength
                                + " bytes (" + (100 * totalRead) / totalFileLength + "%)");

                        //make a final version of the total read to make the handler happy
                        final int totalReadFinal = totalRead;
                        mHandler.post(new Runnable() {
                            public void run() {
                                mProgressNotification.contentView = generateProgressNotificationView(
                                        totalReadFinal, totalFileLength);
                                mNotificationManager.notify(NOTIFICATION_ID, mProgressNotification);
                            }
                        });
                    }
                    bhout.flush();
                    hrout.flush();
                }
            }
            Log.d(this.getClass().getName(), "Finishing upload...");
            // This close is absolutely necessary, this tells the
            // Base64OutputStream to finish writing the last of the data
            // (and including the padding). Without this line, it will miss
            // the last 4 chars in the output, missing up to 3 bytes in the
            // final output.
            bhout.close();
            Log.d(this.getClass().getName(), "Upload complete...");
            mProgressNotification.contentView.setProgressBar(R.id.UploadProgress, totalFileLength, totalRead,
                    false);
        }

        hout.println(boundary);
        hout.flush();
        hrout.close();

        inputStream.close();

        Log.d(this.getClass().getName(), "streams closed, " + "now waiting for response from server");

        final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        final StringBuilder rData = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            rData.append(line).append('\n');
        }

        return rData.toString();
    } catch (final IOException e) {
        Log.e(this.getClass().getName(), "Upload failed", e);
    }

    return null;
}

From source file:com.google.android.gms.samples.vision.face.sleepAlert.DAssistActivity.java

/**
 * Initializes the UI and initiates the creation of a face detector.
 *//*from   w  w  w.jav  a  2 s. c  o m*/
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    mPreview = (CameraSourcePreview) findViewById(R.id.preview);
    mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
    this.jumbleButton = (Button) findViewById(R.id.Button01);
    this.exitButton = (Button) findViewById(R.id.button);
    this.mp = new MediaPlayer();
    this.tv = (TextView) findViewById(R.id.DisplayMsg);
    this.layout = (RelativeLayout) findViewById(R.id.topLayout);
    this.sc = (CameraSourcePreview) findViewById(R.id.preview);
    this.go = (GraphicOverlay) findViewById(R.id.faceOverlay);
    AssetManager am = getApplicationContext().getAssets();
    AssetFileDescriptor afd = null;
    try {
        afd = am.openFd("Song.mp3");
        this.mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
        this.mp.prepare();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Check for the camera permission before accessing the camera.  If the
    // permission is not granted yet, request permission.
    int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
    if (rc == PackageManager.PERMISSION_GRANTED) {
        createCameraSource();
    } else {
        requestCameraPermission();
    }
    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(final MenuItem menuItem) {
            System.out.println("Srini in onNavigationItemSelected part");
            // Handle navigation view item clicks here.
            int id = menuItem.getItemId();

            if (id == R.id.nav_slideshow) {
                // Handle the camera action
            } else if (id == R.id.nav_manage) {

            } else if (id == R.id.nav_manage_toggle) {

                if (checked == 0) {
                    go.setBackgroundColor(Color.TRANSPARENT);
                    checked = 1;
                } else {
                    go.setBackgroundColor(Color.BLUE);
                    checked = 0;

                }

            }

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
            return true;
        }

    });
}

From source file:com.google.dotorg.crisisresponse.translationcards.RecordingActivity.java

private void startListening() {
    recordButton.setBackgroundResource(R.drawable.button_record_disabled);
    listenButton.setBackgroundResource(R.drawable.button_listen_active);
    recordingStatus = RecordingStatus.LISTENING;
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try {//  w w  w  .  ja va  2  s  .c  o  m
        if (isAsset) {
            AssetFileDescriptor fd = getAssets().openFd(filename);
            mediaPlayer.setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getLength());
            fd.close();
        } else {
            mediaPlayer.setDataSource(new FileInputStream(filename).getFD());
        }
        mediaPlayer.prepare();
    } catch (IOException e) {
        Log.d(TAG, "Error preparing audio.");
        throw new IllegalArgumentException(e);
        // TODO(nworden): something
    }
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            finishListening(mp);
        }
    });
    mediaPlayer.start();
}

From source file:se.droidgiro.scanner.CaptureActivity.java

/**
 * Creates the beep MediaPlayer in advance so that the sound can be
 * triggered with the least latency possible.
 *///from   www.j  a  v a2 s .  co  m
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;
        }
    }
}