Example usage for android.content.res AssetFileDescriptor getStartOffset

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

Introduction

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

Prototype

public long getStartOffset() 

Source Link

Document

Returns the byte offset where this asset entry's data starts.

Usage

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;/*from  w  ww .  j  a  v a  2  s.  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() {
            @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);

}

From source file:com.zetterstrom.android.soundboarder.MainActivity.java

public void playSound(AssetFileDescriptor afd) {
    if (mMediaPlayer != null) {
        try {//from   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   ww  w .  j  a v  a  2s . c om
    } else {
        mp.reset();
    }
    mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    mp.prepare();
    mp.setOnCompletionListener(mPlayCompletionListener);
    return mp;
}

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   ww  w.  jav a2 s  .com*/
    // 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.google.android.gms.samples.vision.face.sleepAlert.DAssistActivity.java

/**
 * Initializes the UI and initiates the creation of a face detector.
 *///from w  ww.j a  v  a 2s  .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 .  j  a  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  w  ww  .ja  v  a 2 s.  c  om
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;
        }
    }
}

From source file:org.mercycorps.translationcards.activity.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 {/*from  w  w  w  .  j ava 2s. co 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();
        }
    });
    mediaPlayer.start();
}

From source file:com.eggwall.SoundSleep.AudioService.java

/**
 * Start playing the resource specified here.
 *
 * @param type Either MUSIC, or WHITE_NOISE. Passing the same ID twice
 *             is a signal to stop playing music altogether.
 *//* ww  w .  j av a 2  s .  co m*/
private void play(int type) {
    if (type == MUSIC) {
        final MediaPlayer player = tryStartingMusic();
        if (player != null) {
            mPlayer = player;
            mPlayer.prepareAsync();
            // onPrepared will get called when the media player is ready to play.
            return;
        }
    }
    // Either we weren't able to play custom music, or we were asked to play white noise.
    final int resourceToPlay;
    if (type == WHITE_NOISE) {
        Log.v(TAG, "Playing white noise.");
        resourceToPlay = R.raw.noise;
    } else {
        Log.v(TAG, "Playing included jingle.");
        resourceToPlay = R.raw.jingle;
    }
    try {
        final AssetFileDescriptor d = getResources().openRawResourceFd(resourceToPlay);
        if (d == null) {
            Log.wtf(TAG, "Could not open the file to play");
            return;
        }
        final FileDescriptor fd = d.getFileDescriptor();
        mPlayer = getGenericMediaPlayer();
        mPlayer.setDataSource(fd, d.getStartOffset(), d.getLength());
        d.close();
        // White noise or the default song is looped forever.
        mPlayer.setLooping(true);
    } catch (IOException e) {
        Log.e(TAG, "Could not create a media player instance. Full error below.");
        e.printStackTrace();
        return;
    }
    postSuccessMessage(mTypePlaying);
    mPlayer.prepareAsync();
}

From source file:io.github.carlorodriguez.morningritual.MainActivity.java

private void playLegacyNotificationSound() throws IOException {
    AssetFileDescriptor afd = getResources().openRawResourceFd(R.raw.sound);

    if (afd == null)
        throw new IOException();

    if (mMediaPlayer != null) {
        mMediaPlayer.release();//from   w ww  .j  av  a2s  . c  o m
    }

    mMediaPlayer = new MediaPlayer();

    mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());

    afd.close();

    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);

    mMediaPlayer.prepare();

    mMediaPlayer.start();
}